05c65538c0fa68e16857d230609e918e47606b86
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-tsserver / node_modules / typescript / lib / typingsInstaller.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __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.5";
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         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."),
7525         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."),
7526         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7527         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."),
7528         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."),
7529         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7530         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7531         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."),
7532         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."),
7533         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7534         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7535         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."),
7536         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7537         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."),
7538         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7539         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'."),
7540         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'."),
7541         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7542         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7543         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'."),
7544         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7545         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7546         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7547         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7548         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7549         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7550         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."),
7551         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7552         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7553         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7554         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7555         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7556         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7557         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7558         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7559         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7560         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7561         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7562         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}'."),
7563         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}."),
7564         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}'."),
7565         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7566         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7567         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7568         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."),
7569         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7570         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}."),
7571         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."),
7572         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."),
7573         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."),
7574         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."),
7575         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)."),
7576         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7577         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."),
7578         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7579         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."),
7580         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."),
7581         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)."),
7582         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."),
7583         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7584         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."),
7585         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)."),
7586         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."),
7587         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."),
7588         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."),
7589         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."),
7590         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."),
7591         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."),
7592         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'."),
7593         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."),
7594         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}."),
7595         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."),
7596         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"),
7597         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."),
7598         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7599         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}'."),
7600         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}'."),
7601         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}'. ========"),
7602         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7603         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}'."),
7604         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7605         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}'."),
7606         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}'."),
7607         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}'."),
7608         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7609         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."),
7610         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}'."),
7611         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7612         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."),
7613         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}'."),
7614         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7615         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."),
7616         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}'."),
7617         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}'."),
7618         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}'."),
7619         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}'."),
7620         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}'."),
7621         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}'."),
7622         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7623         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7624         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."),
7625         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7626         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'?"),
7627         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."),
7628         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}'. ========"),
7629         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7630         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7631         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}. ========"),
7632         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. ========"),
7633         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7634         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."),
7635         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. ========"),
7636         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."),
7637         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}'."),
7638         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."),
7639         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}'. ========"),
7640         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. ========"),
7641         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}'."),
7642         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'."),
7643         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."),
7644         _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),
7645         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7646         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7647         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."),
7648         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}'."),
7649         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),
7650         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7651         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}'."),
7652         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."),
7653         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."),
7654         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}'."),
7655         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."),
7656         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'."),
7657         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}'."),
7658         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."),
7659         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7660         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7661         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."),
7662         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."),
7663         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')."),
7664         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."),
7665         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."),
7666         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')"),
7667         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."),
7668         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)."),
7669         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."),
7670         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."),
7671         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."),
7672         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7673         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."),
7674         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."),
7675         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7676         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7677         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'."),
7678         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."),
7679         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7680         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"),
7681         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7682         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7683         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7684         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7685         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7686         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7687         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7688         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7689         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'."),
7690         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7691         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7692         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7693         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."),
7694         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."),
7695         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."),
7696         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7697         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."),
7698         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7699         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."),
7700         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."),
7701         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),
7702         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."),
7703         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."),
7704         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)."),
7705         _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),
7706         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7707         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7708         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7709         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}"),
7710         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7711         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}"),
7712         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7713         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7714         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7715         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."),
7716         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}'."),
7717         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}'."),
7718         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."),
7719         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."),
7720         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."),
7721         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?"),
7722         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?"),
7723         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."),
7724         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}'."),
7725         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7726         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7727         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}'. ========"),
7728         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}. ========"),
7729         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."),
7730         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."),
7731         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."),
7732         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7733         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7734         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'."),
7735         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'."),
7736         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'."),
7737         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."),
7738         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}'."),
7739         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."),
7740         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}."),
7741         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."),
7742         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."),
7743         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7744         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7745         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."),
7746         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}'."),
7747         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."),
7748         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."),
7749         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"),
7750         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"),
7751         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}'"),
7752         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}'"),
7753         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"),
7754         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"),
7755         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"),
7756         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7757         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}"),
7758         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}'"),
7759         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7760         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7761         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"),
7762         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7763         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"),
7764         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"),
7765         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"),
7766         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7767         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7768         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')"),
7769         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"),
7770         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."),
7771         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."),
7772         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}'..."),
7773         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"),
7774         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7775         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}'"),
7776         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}'"),
7777         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}'"),
7778         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}'"),
7779         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7780         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."),
7781         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"),
7782         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}'"),
7783         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"),
7784         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"),
7785         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."),
7786         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}'"),
7787         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."),
7788         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."),
7789         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."),
7790         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?"),
7791         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."),
7792         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."),
7793         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."),
7794         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."),
7795         _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."),
7796         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."),
7797         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."),
7798         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."),
7799         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'."),
7800         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."),
7801         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."),
7802         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."),
7803         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."),
7804         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."),
7805         _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."),
7806         _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."),
7807         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."),
7808         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."),
7809         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."),
7810         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7811         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7812         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7813         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."),
7814         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."),
7815         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."),
7816         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."),
7817         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."),
7818         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}';`"),
7819         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}'."),
7820         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'."),
7821         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."),
7822         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."),
7823         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}`"),
7824         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'."),
7825         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."),
7826         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."),
7827         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."),
7828         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."),
7829         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."),
7830         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."),
7831         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."),
7832         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."),
7833         _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."),
7834         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}'?"),
7835         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}'?"),
7836         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}'."),
7837         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}'."),
7838         _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."),
7839         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
7840         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."),
7841         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."),
7842         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."),
7843         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."),
7844         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."),
7845         _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."),
7846         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."),
7847         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."),
7848         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."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         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}'."),
7854         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}'."),
7855         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
7856         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."),
7857         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."),
7858         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."),
7859         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."),
7860         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."),
7861         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."),
7862         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."),
7863         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."),
7864         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."),
7865         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."),
7866         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."),
7867         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."),
7868         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}'."),
7869         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."),
7870         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
7871         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
7872         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."),
7873         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."),
7874         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'."),
7875         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."),
7876         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}'."),
7877         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
7878         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."),
7879         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'."),
7880         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."),
7881         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."),
7882         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."),
7883         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."),
7884         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
7885         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."),
7886         _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}'?"),
7887         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."),
7888         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."),
7889         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."),
7890         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"),
7891         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"),
7892         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}'?"),
7893         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}"),
7894         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."),
7895         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."),
7896         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}'."),
7897         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."),
7898         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."),
7899         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."),
7900         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."),
7901         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."),
7902         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."),
7903         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."),
7904         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."),
7905         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
7906         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"),
7907         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
7908         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
7909         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
7910         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
7911         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
7912         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
7913         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
7914         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
7915         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
7916         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
7917         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
7918         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
7919         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}\""),
7920         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
7921         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
7922         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
7923         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
7924         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
7925         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
7926         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
7927         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
7928         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
7929         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
7930         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}'"),
7931         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
7932         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
7933         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
7934         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
7935         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
7936         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
7937         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}\""),
7938         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
7939         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
7940         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
7941         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
7942         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
7943         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
7944         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
7945         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
7946         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
7947         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
7948         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
7949         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
7950         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
7951         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
7952         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
7953         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
7954         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
7955         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
7956         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
7957         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
7958         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
7959         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}'"),
7960         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
7961         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
7962         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
7963         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"),
7964         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
7965         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
7966         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"),
7967         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"),
7968         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"),
7969         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)"),
7970         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
7971         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
7972         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
7973         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
7974         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"),
7975         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"),
7976         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
7977         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
7978         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
7979         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
7980         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"),
7981         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
7982         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
7983         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
7984         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
7985         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
7986         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
7987         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
7988         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
7989         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
7990         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
7991         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
7992         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
7993         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
7994         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
7995         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
7996         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"),
7997         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
7998         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
7999         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8000         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8001         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8002         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8003         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8004         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8005         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8006         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8007         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"),
8008         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"),
8009         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8010         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"),
8011         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"),
8012         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"),
8013         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8014         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8015         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8016         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8017         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8018         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"),
8019         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8020         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8021         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8022         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8023         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8024         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8025         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8026         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"),
8027         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8028         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8029         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8030         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8031         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8032         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8033         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'"),
8034         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8035         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"),
8036         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}'"),
8037         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}'"),
8038         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"),
8039         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"),
8040         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8041         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8042         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8043         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"),
8044         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"),
8045         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8046         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"),
8047         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"),
8048         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"),
8049         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8050         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8051         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"),
8052         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8053         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8054         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8055         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."),
8056         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'."),
8057         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?"),
8058         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"),
8059         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."),
8060         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."),
8061         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8062         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."),
8063         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."),
8064         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}'."),
8065         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."),
8066         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"),
8067         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"),
8068         _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"),
8069         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."),
8070         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."),
8071         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."),
8072         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."),
8073         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."),
8074         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."),
8075         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."),
8076         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."),
8077         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."),
8078         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."),
8079         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."),
8080     };
8081 })(ts || (ts = {}));
8082 var ts;
8083 (function (ts) {
8084     var _a;
8085     /* @internal */
8086     function tokenIsIdentifierOrKeyword(token) {
8087         return token >= 75 /* Identifier */;
8088     }
8089     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8090     /* @internal */
8091     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8092         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8093     }
8094     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8095     var textToKeywordObj = (_a = {
8096             abstract: 122 /* AbstractKeyword */,
8097             any: 125 /* AnyKeyword */,
8098             as: 123 /* AsKeyword */,
8099             asserts: 124 /* AssertsKeyword */,
8100             bigint: 151 /* BigIntKeyword */,
8101             boolean: 128 /* BooleanKeyword */,
8102             break: 77 /* BreakKeyword */,
8103             case: 78 /* CaseKeyword */,
8104             catch: 79 /* CatchKeyword */,
8105             class: 80 /* ClassKeyword */,
8106             continue: 82 /* ContinueKeyword */,
8107             const: 81 /* ConstKeyword */
8108         },
8109         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8110         _a.debugger = 83 /* DebuggerKeyword */,
8111         _a.declare = 130 /* DeclareKeyword */,
8112         _a.default = 84 /* DefaultKeyword */,
8113         _a.delete = 85 /* DeleteKeyword */,
8114         _a.do = 86 /* DoKeyword */,
8115         _a.else = 87 /* ElseKeyword */,
8116         _a.enum = 88 /* EnumKeyword */,
8117         _a.export = 89 /* ExportKeyword */,
8118         _a.extends = 90 /* ExtendsKeyword */,
8119         _a.false = 91 /* FalseKeyword */,
8120         _a.finally = 92 /* FinallyKeyword */,
8121         _a.for = 93 /* ForKeyword */,
8122         _a.from = 149 /* FromKeyword */,
8123         _a.function = 94 /* FunctionKeyword */,
8124         _a.get = 131 /* GetKeyword */,
8125         _a.if = 95 /* IfKeyword */,
8126         _a.implements = 113 /* ImplementsKeyword */,
8127         _a.import = 96 /* ImportKeyword */,
8128         _a.in = 97 /* InKeyword */,
8129         _a.infer = 132 /* InferKeyword */,
8130         _a.instanceof = 98 /* InstanceOfKeyword */,
8131         _a.interface = 114 /* InterfaceKeyword */,
8132         _a.is = 133 /* IsKeyword */,
8133         _a.keyof = 134 /* KeyOfKeyword */,
8134         _a.let = 115 /* LetKeyword */,
8135         _a.module = 135 /* ModuleKeyword */,
8136         _a.namespace = 136 /* NamespaceKeyword */,
8137         _a.never = 137 /* NeverKeyword */,
8138         _a.new = 99 /* NewKeyword */,
8139         _a.null = 100 /* NullKeyword */,
8140         _a.number = 140 /* NumberKeyword */,
8141         _a.object = 141 /* ObjectKeyword */,
8142         _a.package = 116 /* PackageKeyword */,
8143         _a.private = 117 /* PrivateKeyword */,
8144         _a.protected = 118 /* ProtectedKeyword */,
8145         _a.public = 119 /* PublicKeyword */,
8146         _a.readonly = 138 /* ReadonlyKeyword */,
8147         _a.require = 139 /* RequireKeyword */,
8148         _a.global = 150 /* GlobalKeyword */,
8149         _a.return = 101 /* ReturnKeyword */,
8150         _a.set = 142 /* SetKeyword */,
8151         _a.static = 120 /* StaticKeyword */,
8152         _a.string = 143 /* StringKeyword */,
8153         _a.super = 102 /* SuperKeyword */,
8154         _a.switch = 103 /* SwitchKeyword */,
8155         _a.symbol = 144 /* SymbolKeyword */,
8156         _a.this = 104 /* ThisKeyword */,
8157         _a.throw = 105 /* ThrowKeyword */,
8158         _a.true = 106 /* TrueKeyword */,
8159         _a.try = 107 /* TryKeyword */,
8160         _a.type = 145 /* TypeKeyword */,
8161         _a.typeof = 108 /* TypeOfKeyword */,
8162         _a.undefined = 146 /* UndefinedKeyword */,
8163         _a.unique = 147 /* UniqueKeyword */,
8164         _a.unknown = 148 /* UnknownKeyword */,
8165         _a.var = 109 /* VarKeyword */,
8166         _a.void = 110 /* VoidKeyword */,
8167         _a.while = 111 /* WhileKeyword */,
8168         _a.with = 112 /* WithKeyword */,
8169         _a.yield = 121 /* YieldKeyword */,
8170         _a.async = 126 /* AsyncKeyword */,
8171         _a.await = 127 /* AwaitKeyword */,
8172         _a.of = 152 /* OfKeyword */,
8173         _a);
8174     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8175     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 */ }));
8176     /*
8177         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8178         IdentifierStart ::
8179             Can contain Unicode 3.0.0 categories:
8180             Uppercase letter (Lu),
8181             Lowercase letter (Ll),
8182             Titlecase letter (Lt),
8183             Modifier letter (Lm),
8184             Other letter (Lo), or
8185             Letter number (Nl).
8186         IdentifierPart :: =
8187             Can contain IdentifierStart + Unicode 3.0.0 categories:
8188             Non-spacing mark (Mn),
8189             Combining spacing mark (Mc),
8190             Decimal number (Nd), or
8191             Connector punctuation (Pc).
8192
8193         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8194         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8195     */
8196     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,];
8197     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,];
8198     /*
8199         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8200         IdentifierStart ::
8201             Can contain Unicode 6.2 categories:
8202             Uppercase letter (Lu),
8203             Lowercase letter (Ll),
8204             Titlecase letter (Lt),
8205             Modifier letter (Lm),
8206             Other letter (Lo), or
8207             Letter number (Nl).
8208         IdentifierPart ::
8209             Can contain IdentifierStart + Unicode 6.2 categories:
8210             Non-spacing mark (Mn),
8211             Combining spacing mark (Mc),
8212             Decimal number (Nd),
8213             Connector punctuation (Pc),
8214             <ZWNJ>, or
8215             <ZWJ>.
8216
8217         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8218         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8219     */
8220     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,];
8221     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,];
8222     /**
8223      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8224      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8225      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8226      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8227      */
8228     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];
8229     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];
8230     /**
8231      * Test for whether a single line comment's text contains a directive.
8232      */
8233     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8234     /**
8235      * Test for whether a multi-line comment's last line contains a directive.
8236      */
8237     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8238     function lookupInUnicodeMap(code, map) {
8239         // Bail out quickly if it couldn't possibly be in the map.
8240         if (code < map[0]) {
8241             return false;
8242         }
8243         // Perform binary search in one of the Unicode range maps
8244         var lo = 0;
8245         var hi = map.length;
8246         var mid;
8247         while (lo + 1 < hi) {
8248             mid = lo + (hi - lo) / 2;
8249             // mid has to be even to catch a range's beginning
8250             mid -= mid % 2;
8251             if (map[mid] <= code && code <= map[mid + 1]) {
8252                 return true;
8253             }
8254             if (code < map[mid]) {
8255                 hi = mid;
8256             }
8257             else {
8258                 lo = mid + 2;
8259             }
8260         }
8261         return false;
8262     }
8263     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8264         return languageVersion >= 2 /* ES2015 */ ?
8265             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8266             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8267                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8268     }
8269     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8270     function isUnicodeIdentifierPart(code, languageVersion) {
8271         return languageVersion >= 2 /* ES2015 */ ?
8272             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8273             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8274                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8275     }
8276     function makeReverseMap(source) {
8277         var result = [];
8278         source.forEach(function (value, name) {
8279             result[value] = name;
8280         });
8281         return result;
8282     }
8283     var tokenStrings = makeReverseMap(textToToken);
8284     function tokenToString(t) {
8285         return tokenStrings[t];
8286     }
8287     ts.tokenToString = tokenToString;
8288     /* @internal */
8289     function stringToToken(s) {
8290         return textToToken.get(s);
8291     }
8292     ts.stringToToken = stringToToken;
8293     /* @internal */
8294     function computeLineStarts(text) {
8295         var result = new Array();
8296         var pos = 0;
8297         var lineStart = 0;
8298         while (pos < text.length) {
8299             var ch = text.charCodeAt(pos);
8300             pos++;
8301             switch (ch) {
8302                 case 13 /* carriageReturn */:
8303                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8304                         pos++;
8305                     }
8306                 // falls through
8307                 case 10 /* lineFeed */:
8308                     result.push(lineStart);
8309                     lineStart = pos;
8310                     break;
8311                 default:
8312                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8313                         result.push(lineStart);
8314                         lineStart = pos;
8315                     }
8316                     break;
8317             }
8318         }
8319         result.push(lineStart);
8320         return result;
8321     }
8322     ts.computeLineStarts = computeLineStarts;
8323     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8324         return sourceFile.getPositionOfLineAndCharacter ?
8325             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8326             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8327     }
8328     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8329     /* @internal */
8330     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8331         if (line < 0 || line >= lineStarts.length) {
8332             if (allowEdits) {
8333                 // Clamp line to nearest allowable value
8334                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8335             }
8336             else {
8337                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8338             }
8339         }
8340         var res = lineStarts[line] + character;
8341         if (allowEdits) {
8342             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8343             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8344             // apply them to the computed position to improve accuracy
8345             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8346         }
8347         if (line < lineStarts.length - 1) {
8348             ts.Debug.assert(res < lineStarts[line + 1]);
8349         }
8350         else if (debugText !== undefined) {
8351             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8352         }
8353         return res;
8354     }
8355     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8356     /* @internal */
8357     function getLineStarts(sourceFile) {
8358         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8359     }
8360     ts.getLineStarts = getLineStarts;
8361     /* @internal */
8362     function computeLineAndCharacterOfPosition(lineStarts, position) {
8363         var lineNumber = computeLineOfPosition(lineStarts, position);
8364         return {
8365             line: lineNumber,
8366             character: position - lineStarts[lineNumber]
8367         };
8368     }
8369     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8370     /**
8371      * @internal
8372      * We assume the first line starts at position 0 and 'position' is non-negative.
8373      */
8374     function computeLineOfPosition(lineStarts, position, lowerBound) {
8375         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8376         if (lineNumber < 0) {
8377             // If the actual position was not found,
8378             // the binary search returns the 2's-complement of the next line start
8379             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8380             // then the search will return -2.
8381             //
8382             // We want the index of the previous line start, so we subtract 1.
8383             // Review 2's-complement if this is confusing.
8384             lineNumber = ~lineNumber - 1;
8385             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8386         }
8387         return lineNumber;
8388     }
8389     ts.computeLineOfPosition = computeLineOfPosition;
8390     /** @internal */
8391     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8392         if (pos1 === pos2)
8393             return 0;
8394         var lineStarts = getLineStarts(sourceFile);
8395         var lower = Math.min(pos1, pos2);
8396         var isNegative = lower === pos2;
8397         var upper = isNegative ? pos1 : pos2;
8398         var lowerLine = computeLineOfPosition(lineStarts, lower);
8399         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8400         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8401     }
8402     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8403     function getLineAndCharacterOfPosition(sourceFile, position) {
8404         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8405     }
8406     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8407     function isWhiteSpaceLike(ch) {
8408         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8409     }
8410     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8411     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8412     function isWhiteSpaceSingleLine(ch) {
8413         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8414         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8415         return ch === 32 /* space */ ||
8416             ch === 9 /* tab */ ||
8417             ch === 11 /* verticalTab */ ||
8418             ch === 12 /* formFeed */ ||
8419             ch === 160 /* nonBreakingSpace */ ||
8420             ch === 133 /* nextLine */ ||
8421             ch === 5760 /* ogham */ ||
8422             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8423             ch === 8239 /* narrowNoBreakSpace */ ||
8424             ch === 8287 /* mathematicalSpace */ ||
8425             ch === 12288 /* ideographicSpace */ ||
8426             ch === 65279 /* byteOrderMark */;
8427     }
8428     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8429     function isLineBreak(ch) {
8430         // ES5 7.3:
8431         // The ECMAScript line terminator characters are listed in Table 3.
8432         //     Table 3: Line Terminator Characters
8433         //     Code Unit Value     Name                    Formal Name
8434         //     \u000A              Line Feed               <LF>
8435         //     \u000D              Carriage Return         <CR>
8436         //     \u2028              Line separator          <LS>
8437         //     \u2029              Paragraph separator     <PS>
8438         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8439         // breaking characters are treated as white space but not as line terminators.
8440         return ch === 10 /* lineFeed */ ||
8441             ch === 13 /* carriageReturn */ ||
8442             ch === 8232 /* lineSeparator */ ||
8443             ch === 8233 /* paragraphSeparator */;
8444     }
8445     ts.isLineBreak = isLineBreak;
8446     function isDigit(ch) {
8447         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8448     }
8449     function isHexDigit(ch) {
8450         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8451     }
8452     function isCodePoint(code) {
8453         return code <= 0x10FFFF;
8454     }
8455     /* @internal */
8456     function isOctalDigit(ch) {
8457         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8458     }
8459     ts.isOctalDigit = isOctalDigit;
8460     function couldStartTrivia(text, pos) {
8461         // Keep in sync with skipTrivia
8462         var ch = text.charCodeAt(pos);
8463         switch (ch) {
8464             case 13 /* carriageReturn */:
8465             case 10 /* lineFeed */:
8466             case 9 /* tab */:
8467             case 11 /* verticalTab */:
8468             case 12 /* formFeed */:
8469             case 32 /* space */:
8470             case 47 /* slash */:
8471             // starts of normal trivia
8472             // falls through
8473             case 60 /* lessThan */:
8474             case 124 /* bar */:
8475             case 61 /* equals */:
8476             case 62 /* greaterThan */:
8477                 // Starts of conflict marker trivia
8478                 return true;
8479             case 35 /* hash */:
8480                 // Only if its the beginning can we have #! trivia
8481                 return pos === 0;
8482             default:
8483                 return ch > 127 /* maxAsciiCharacter */;
8484         }
8485     }
8486     ts.couldStartTrivia = couldStartTrivia;
8487     /* @internal */
8488     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8489         if (stopAtComments === void 0) { stopAtComments = false; }
8490         if (ts.positionIsSynthesized(pos)) {
8491             return pos;
8492         }
8493         // Keep in sync with couldStartTrivia
8494         while (true) {
8495             var ch = text.charCodeAt(pos);
8496             switch (ch) {
8497                 case 13 /* carriageReturn */:
8498                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8499                         pos++;
8500                     }
8501                 // falls through
8502                 case 10 /* lineFeed */:
8503                     pos++;
8504                     if (stopAfterLineBreak) {
8505                         return pos;
8506                     }
8507                     continue;
8508                 case 9 /* tab */:
8509                 case 11 /* verticalTab */:
8510                 case 12 /* formFeed */:
8511                 case 32 /* space */:
8512                     pos++;
8513                     continue;
8514                 case 47 /* slash */:
8515                     if (stopAtComments) {
8516                         break;
8517                     }
8518                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8519                         pos += 2;
8520                         while (pos < text.length) {
8521                             if (isLineBreak(text.charCodeAt(pos))) {
8522                                 break;
8523                             }
8524                             pos++;
8525                         }
8526                         continue;
8527                     }
8528                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8529                         pos += 2;
8530                         while (pos < text.length) {
8531                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8532                                 pos += 2;
8533                                 break;
8534                             }
8535                             pos++;
8536                         }
8537                         continue;
8538                     }
8539                     break;
8540                 case 60 /* lessThan */:
8541                 case 124 /* bar */:
8542                 case 61 /* equals */:
8543                 case 62 /* greaterThan */:
8544                     if (isConflictMarkerTrivia(text, pos)) {
8545                         pos = scanConflictMarkerTrivia(text, pos);
8546                         continue;
8547                     }
8548                     break;
8549                 case 35 /* hash */:
8550                     if (pos === 0 && isShebangTrivia(text, pos)) {
8551                         pos = scanShebangTrivia(text, pos);
8552                         continue;
8553                     }
8554                     break;
8555                 default:
8556                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8557                         pos++;
8558                         continue;
8559                     }
8560                     break;
8561             }
8562             return pos;
8563         }
8564     }
8565     ts.skipTrivia = skipTrivia;
8566     // All conflict markers consist of the same character repeated seven times.  If it is
8567     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8568     var mergeConflictMarkerLength = "<<<<<<<".length;
8569     function isConflictMarkerTrivia(text, pos) {
8570         ts.Debug.assert(pos >= 0);
8571         // Conflict markers must be at the start of a line.
8572         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8573             var ch = text.charCodeAt(pos);
8574             if ((pos + mergeConflictMarkerLength) < text.length) {
8575                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8576                     if (text.charCodeAt(pos + i) !== ch) {
8577                         return false;
8578                     }
8579                 }
8580                 return ch === 61 /* equals */ ||
8581                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8582             }
8583         }
8584         return false;
8585     }
8586     function scanConflictMarkerTrivia(text, pos, error) {
8587         if (error) {
8588             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8589         }
8590         var ch = text.charCodeAt(pos);
8591         var len = text.length;
8592         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8593             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8594                 pos++;
8595             }
8596         }
8597         else {
8598             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8599             // Consume everything from the start of a ||||||| or ======= marker to the start
8600             // of the next ======= or >>>>>>> marker.
8601             while (pos < len) {
8602                 var currentChar = text.charCodeAt(pos);
8603                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8604                     break;
8605                 }
8606                 pos++;
8607             }
8608         }
8609         return pos;
8610     }
8611     var shebangTriviaRegex = /^#!.*/;
8612     /*@internal*/
8613     function isShebangTrivia(text, pos) {
8614         // Shebangs check must only be done at the start of the file
8615         ts.Debug.assert(pos === 0);
8616         return shebangTriviaRegex.test(text);
8617     }
8618     ts.isShebangTrivia = isShebangTrivia;
8619     /*@internal*/
8620     function scanShebangTrivia(text, pos) {
8621         var shebang = shebangTriviaRegex.exec(text)[0];
8622         pos = pos + shebang.length;
8623         return pos;
8624     }
8625     ts.scanShebangTrivia = scanShebangTrivia;
8626     /**
8627      * Invokes a callback for each comment range following the provided position.
8628      *
8629      * Single-line comment ranges include the leading double-slash characters but not the ending
8630      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8631      * asterisk-slash characters.
8632      *
8633      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8634      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8635      * @param text The source text to scan.
8636      * @param pos The position at which to start scanning.
8637      * @param trailing If false, whitespace is skipped until the first line break and comments
8638      *      between that location and the next token are returned. If true, comments occurring
8639      *      between the given position and the next line break are returned.
8640      * @param cb The callback to execute as each comment range is encountered.
8641      * @param state A state value to pass to each iteration of the callback.
8642      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8643      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8644      *      return value of the callback.
8645      */
8646     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8647         var pendingPos;
8648         var pendingEnd;
8649         var pendingKind;
8650         var pendingHasTrailingNewLine;
8651         var hasPendingCommentRange = false;
8652         var collecting = trailing;
8653         var accumulator = initial;
8654         if (pos === 0) {
8655             collecting = true;
8656             var shebang = getShebang(text);
8657             if (shebang) {
8658                 pos = shebang.length;
8659             }
8660         }
8661         scan: while (pos >= 0 && pos < text.length) {
8662             var ch = text.charCodeAt(pos);
8663             switch (ch) {
8664                 case 13 /* carriageReturn */:
8665                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8666                         pos++;
8667                     }
8668                 // falls through
8669                 case 10 /* lineFeed */:
8670                     pos++;
8671                     if (trailing) {
8672                         break scan;
8673                     }
8674                     collecting = true;
8675                     if (hasPendingCommentRange) {
8676                         pendingHasTrailingNewLine = true;
8677                     }
8678                     continue;
8679                 case 9 /* tab */:
8680                 case 11 /* verticalTab */:
8681                 case 12 /* formFeed */:
8682                 case 32 /* space */:
8683                     pos++;
8684                     continue;
8685                 case 47 /* slash */:
8686                     var nextChar = text.charCodeAt(pos + 1);
8687                     var hasTrailingNewLine = false;
8688                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8689                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8690                         var startPos = pos;
8691                         pos += 2;
8692                         if (nextChar === 47 /* slash */) {
8693                             while (pos < text.length) {
8694                                 if (isLineBreak(text.charCodeAt(pos))) {
8695                                     hasTrailingNewLine = true;
8696                                     break;
8697                                 }
8698                                 pos++;
8699                             }
8700                         }
8701                         else {
8702                             while (pos < text.length) {
8703                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8704                                     pos += 2;
8705                                     break;
8706                                 }
8707                                 pos++;
8708                             }
8709                         }
8710                         if (collecting) {
8711                             if (hasPendingCommentRange) {
8712                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8713                                 if (!reduce && accumulator) {
8714                                     // If we are not reducing and we have a truthy result, return it.
8715                                     return accumulator;
8716                                 }
8717                             }
8718                             pendingPos = startPos;
8719                             pendingEnd = pos;
8720                             pendingKind = kind;
8721                             pendingHasTrailingNewLine = hasTrailingNewLine;
8722                             hasPendingCommentRange = true;
8723                         }
8724                         continue;
8725                     }
8726                     break scan;
8727                 default:
8728                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8729                         if (hasPendingCommentRange && isLineBreak(ch)) {
8730                             pendingHasTrailingNewLine = true;
8731                         }
8732                         pos++;
8733                         continue;
8734                     }
8735                     break scan;
8736             }
8737         }
8738         if (hasPendingCommentRange) {
8739             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8740         }
8741         return accumulator;
8742     }
8743     function forEachLeadingCommentRange(text, pos, cb, state) {
8744         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8745     }
8746     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8747     function forEachTrailingCommentRange(text, pos, cb, state) {
8748         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8749     }
8750     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8751     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8752         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8753     }
8754     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8755     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8756         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8757     }
8758     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8759     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8760         if (!comments) {
8761             comments = [];
8762         }
8763         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8764         return comments;
8765     }
8766     function getLeadingCommentRanges(text, pos) {
8767         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8768     }
8769     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8770     function getTrailingCommentRanges(text, pos) {
8771         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8772     }
8773     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8774     /** Optionally, get the shebang */
8775     function getShebang(text) {
8776         var match = shebangTriviaRegex.exec(text);
8777         if (match) {
8778             return match[0];
8779         }
8780     }
8781     ts.getShebang = getShebang;
8782     function isIdentifierStart(ch, languageVersion) {
8783         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8784             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8785             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8786     }
8787     ts.isIdentifierStart = isIdentifierStart;
8788     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8789         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8790             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8791             // "-" and ":" are valid in JSX Identifiers
8792             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8793             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8794     }
8795     ts.isIdentifierPart = isIdentifierPart;
8796     /* @internal */
8797     function isIdentifierText(name, languageVersion, identifierVariant) {
8798         var ch = codePointAt(name, 0);
8799         if (!isIdentifierStart(ch, languageVersion)) {
8800             return false;
8801         }
8802         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8803             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8804                 return false;
8805             }
8806         }
8807         return true;
8808     }
8809     ts.isIdentifierText = isIdentifierText;
8810     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8811     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8812         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8813         var text = textInitial;
8814         // Current position (end position of text of current token)
8815         var pos;
8816         // end of text
8817         var end;
8818         // Start position of whitespace before current token
8819         var startPos;
8820         // Start position of text of current token
8821         var tokenPos;
8822         var token;
8823         var tokenValue;
8824         var tokenFlags;
8825         var commentDirectives;
8826         var inJSDocType = 0;
8827         setText(text, start, length);
8828         var scanner = {
8829             getStartPos: function () { return startPos; },
8830             getTextPos: function () { return pos; },
8831             getToken: function () { return token; },
8832             getTokenPos: function () { return tokenPos; },
8833             getTokenText: function () { return text.substring(tokenPos, pos); },
8834             getTokenValue: function () { return tokenValue; },
8835             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8836             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8837             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
8838             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
8839             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
8840             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
8841             getCommentDirectives: function () { return commentDirectives; },
8842             getTokenFlags: function () { return tokenFlags; },
8843             reScanGreaterToken: reScanGreaterToken,
8844             reScanSlashToken: reScanSlashToken,
8845             reScanTemplateToken: reScanTemplateToken,
8846             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
8847             scanJsxIdentifier: scanJsxIdentifier,
8848             scanJsxAttributeValue: scanJsxAttributeValue,
8849             reScanJsxAttributeValue: reScanJsxAttributeValue,
8850             reScanJsxToken: reScanJsxToken,
8851             reScanLessThanToken: reScanLessThanToken,
8852             reScanQuestionToken: reScanQuestionToken,
8853             scanJsxToken: scanJsxToken,
8854             scanJsDocToken: scanJsDocToken,
8855             scan: scan,
8856             getText: getText,
8857             clearCommentDirectives: clearCommentDirectives,
8858             setText: setText,
8859             setScriptTarget: setScriptTarget,
8860             setLanguageVariant: setLanguageVariant,
8861             setOnError: setOnError,
8862             setTextPos: setTextPos,
8863             setInJSDocType: setInJSDocType,
8864             tryScan: tryScan,
8865             lookAhead: lookAhead,
8866             scanRange: scanRange,
8867         };
8868         if (ts.Debug.isDebugging) {
8869             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
8870                 get: function () {
8871                     var text = scanner.getText();
8872                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
8873                 },
8874             });
8875         }
8876         return scanner;
8877         function error(message, errPos, length) {
8878             if (errPos === void 0) { errPos = pos; }
8879             if (onError) {
8880                 var oldPos = pos;
8881                 pos = errPos;
8882                 onError(message, length || 0);
8883                 pos = oldPos;
8884             }
8885         }
8886         function scanNumberFragment() {
8887             var start = pos;
8888             var allowSeparator = false;
8889             var isPreviousTokenSeparator = false;
8890             var result = "";
8891             while (true) {
8892                 var ch = text.charCodeAt(pos);
8893                 if (ch === 95 /* _ */) {
8894                     tokenFlags |= 512 /* ContainsSeparator */;
8895                     if (allowSeparator) {
8896                         allowSeparator = false;
8897                         isPreviousTokenSeparator = true;
8898                         result += text.substring(start, pos);
8899                     }
8900                     else if (isPreviousTokenSeparator) {
8901                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
8902                     }
8903                     else {
8904                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
8905                     }
8906                     pos++;
8907                     start = pos;
8908                     continue;
8909                 }
8910                 if (isDigit(ch)) {
8911                     allowSeparator = true;
8912                     isPreviousTokenSeparator = false;
8913                     pos++;
8914                     continue;
8915                 }
8916                 break;
8917             }
8918             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
8919                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
8920             }
8921             return result + text.substring(start, pos);
8922         }
8923         function scanNumber() {
8924             var start = pos;
8925             var mainFragment = scanNumberFragment();
8926             var decimalFragment;
8927             var scientificFragment;
8928             if (text.charCodeAt(pos) === 46 /* dot */) {
8929                 pos++;
8930                 decimalFragment = scanNumberFragment();
8931             }
8932             var end = pos;
8933             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
8934                 pos++;
8935                 tokenFlags |= 16 /* Scientific */;
8936                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
8937                     pos++;
8938                 var preNumericPart = pos;
8939                 var finalFragment = scanNumberFragment();
8940                 if (!finalFragment) {
8941                     error(ts.Diagnostics.Digit_expected);
8942                 }
8943                 else {
8944                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
8945                     end = pos;
8946                 }
8947             }
8948             var result;
8949             if (tokenFlags & 512 /* ContainsSeparator */) {
8950                 result = mainFragment;
8951                 if (decimalFragment) {
8952                     result += "." + decimalFragment;
8953                 }
8954                 if (scientificFragment) {
8955                     result += scientificFragment;
8956                 }
8957             }
8958             else {
8959                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
8960             }
8961             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
8962                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
8963                 return {
8964                     type: 8 /* NumericLiteral */,
8965                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
8966                 };
8967             }
8968             else {
8969                 tokenValue = result;
8970                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
8971                 checkForIdentifierStartAfterNumericLiteral(start);
8972                 return { type: type, value: tokenValue };
8973             }
8974         }
8975         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
8976             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
8977                 return;
8978             }
8979             var identifierStart = pos;
8980             var length = scanIdentifierParts().length;
8981             if (length === 1 && text[identifierStart] === "n") {
8982                 if (isScientific) {
8983                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
8984                 }
8985                 else {
8986                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
8987                 }
8988             }
8989             else {
8990                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
8991                 pos = identifierStart;
8992             }
8993         }
8994         function scanOctalDigits() {
8995             var start = pos;
8996             while (isOctalDigit(text.charCodeAt(pos))) {
8997                 pos++;
8998             }
8999             return +(text.substring(start, pos));
9000         }
9001         /**
9002          * Scans the given number of hexadecimal digits in the text,
9003          * returning -1 if the given number is unavailable.
9004          */
9005         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9006             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9007             return valueString ? parseInt(valueString, 16) : -1;
9008         }
9009         /**
9010          * Scans as many hexadecimal digits as are available in the text,
9011          * returning "" if the given number of digits was unavailable.
9012          */
9013         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9014             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9015         }
9016         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9017             var valueChars = [];
9018             var allowSeparator = false;
9019             var isPreviousTokenSeparator = false;
9020             while (valueChars.length < minCount || scanAsManyAsPossible) {
9021                 var ch = text.charCodeAt(pos);
9022                 if (canHaveSeparators && ch === 95 /* _ */) {
9023                     tokenFlags |= 512 /* ContainsSeparator */;
9024                     if (allowSeparator) {
9025                         allowSeparator = false;
9026                         isPreviousTokenSeparator = true;
9027                     }
9028                     else if (isPreviousTokenSeparator) {
9029                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9030                     }
9031                     else {
9032                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9033                     }
9034                     pos++;
9035                     continue;
9036                 }
9037                 allowSeparator = canHaveSeparators;
9038                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9039                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9040                 }
9041                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9042                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9043                     break;
9044                 }
9045                 valueChars.push(ch);
9046                 pos++;
9047                 isPreviousTokenSeparator = false;
9048             }
9049             if (valueChars.length < minCount) {
9050                 valueChars = [];
9051             }
9052             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9053                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9054             }
9055             return String.fromCharCode.apply(String, valueChars);
9056         }
9057         function scanString(jsxAttributeString) {
9058             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9059             var quote = text.charCodeAt(pos);
9060             pos++;
9061             var result = "";
9062             var start = pos;
9063             while (true) {
9064                 if (pos >= end) {
9065                     result += text.substring(start, pos);
9066                     tokenFlags |= 4 /* Unterminated */;
9067                     error(ts.Diagnostics.Unterminated_string_literal);
9068                     break;
9069                 }
9070                 var ch = text.charCodeAt(pos);
9071                 if (ch === quote) {
9072                     result += text.substring(start, pos);
9073                     pos++;
9074                     break;
9075                 }
9076                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9077                     result += text.substring(start, pos);
9078                     result += scanEscapeSequence();
9079                     start = pos;
9080                     continue;
9081                 }
9082                 if (isLineBreak(ch) && !jsxAttributeString) {
9083                     result += text.substring(start, pos);
9084                     tokenFlags |= 4 /* Unterminated */;
9085                     error(ts.Diagnostics.Unterminated_string_literal);
9086                     break;
9087                 }
9088                 pos++;
9089             }
9090             return result;
9091         }
9092         /**
9093          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9094          * a literal component of a TemplateExpression.
9095          */
9096         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9097             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9098             pos++;
9099             var start = pos;
9100             var contents = "";
9101             var resultingToken;
9102             while (true) {
9103                 if (pos >= end) {
9104                     contents += text.substring(start, pos);
9105                     tokenFlags |= 4 /* Unterminated */;
9106                     error(ts.Diagnostics.Unterminated_template_literal);
9107                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9108                     break;
9109                 }
9110                 var currChar = text.charCodeAt(pos);
9111                 // '`'
9112                 if (currChar === 96 /* backtick */) {
9113                     contents += text.substring(start, pos);
9114                     pos++;
9115                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9116                     break;
9117                 }
9118                 // '${'
9119                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9120                     contents += text.substring(start, pos);
9121                     pos += 2;
9122                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9123                     break;
9124                 }
9125                 // Escape character
9126                 if (currChar === 92 /* backslash */) {
9127                     contents += text.substring(start, pos);
9128                     contents += scanEscapeSequence(isTaggedTemplate);
9129                     start = pos;
9130                     continue;
9131                 }
9132                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9133                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9134                 if (currChar === 13 /* carriageReturn */) {
9135                     contents += text.substring(start, pos);
9136                     pos++;
9137                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9138                         pos++;
9139                     }
9140                     contents += "\n";
9141                     start = pos;
9142                     continue;
9143                 }
9144                 pos++;
9145             }
9146             ts.Debug.assert(resultingToken !== undefined);
9147             tokenValue = contents;
9148             return resultingToken;
9149         }
9150         function scanEscapeSequence(isTaggedTemplate) {
9151             var start = pos;
9152             pos++;
9153             if (pos >= end) {
9154                 error(ts.Diagnostics.Unexpected_end_of_text);
9155                 return "";
9156             }
9157             var ch = text.charCodeAt(pos);
9158             pos++;
9159             switch (ch) {
9160                 case 48 /* _0 */:
9161                     // '\01'
9162                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9163                         pos++;
9164                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9165                         return text.substring(start, pos);
9166                     }
9167                     return "\0";
9168                 case 98 /* b */:
9169                     return "\b";
9170                 case 116 /* t */:
9171                     return "\t";
9172                 case 110 /* n */:
9173                     return "\n";
9174                 case 118 /* v */:
9175                     return "\v";
9176                 case 102 /* f */:
9177                     return "\f";
9178                 case 114 /* r */:
9179                     return "\r";
9180                 case 39 /* singleQuote */:
9181                     return "\'";
9182                 case 34 /* doubleQuote */:
9183                     return "\"";
9184                 case 117 /* u */:
9185                     if (isTaggedTemplate) {
9186                         // '\u' or '\u0' or '\u00' or '\u000'
9187                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9188                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9189                                 pos = escapePos;
9190                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9191                                 return text.substring(start, pos);
9192                             }
9193                         }
9194                     }
9195                     // '\u{DDDDDDDD}'
9196                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9197                         pos++;
9198                         // '\u{'
9199                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9200                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9201                             return text.substring(start, pos);
9202                         }
9203                         if (isTaggedTemplate) {
9204                             var savePos = pos;
9205                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9206                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9207                             // '\u{Not Code Point' or '\u{CodePoint'
9208                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9209                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9210                                 return text.substring(start, pos);
9211                             }
9212                             else {
9213                                 pos = savePos;
9214                             }
9215                         }
9216                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9217                         return scanExtendedUnicodeEscape();
9218                     }
9219                     tokenFlags |= 1024 /* UnicodeEscape */;
9220                     // '\uDDDD'
9221                     return scanHexadecimalEscape(/*numDigits*/ 4);
9222                 case 120 /* x */:
9223                     if (isTaggedTemplate) {
9224                         if (!isHexDigit(text.charCodeAt(pos))) {
9225                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9226                             return text.substring(start, pos);
9227                         }
9228                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9229                             pos++;
9230                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9231                             return text.substring(start, pos);
9232                         }
9233                     }
9234                     // '\xDD'
9235                     return scanHexadecimalEscape(/*numDigits*/ 2);
9236                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9237                 // the line terminator is interpreted to be "the empty code unit sequence".
9238                 case 13 /* carriageReturn */:
9239                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9240                         pos++;
9241                     }
9242                 // falls through
9243                 case 10 /* lineFeed */:
9244                 case 8232 /* lineSeparator */:
9245                 case 8233 /* paragraphSeparator */:
9246                     return "";
9247                 default:
9248                     return String.fromCharCode(ch);
9249             }
9250         }
9251         function scanHexadecimalEscape(numDigits) {
9252             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9253             if (escapedValue >= 0) {
9254                 return String.fromCharCode(escapedValue);
9255             }
9256             else {
9257                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9258                 return "";
9259             }
9260         }
9261         function scanExtendedUnicodeEscape() {
9262             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9263             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9264             var isInvalidExtendedEscape = false;
9265             // Validate the value of the digit
9266             if (escapedValue < 0) {
9267                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9268                 isInvalidExtendedEscape = true;
9269             }
9270             else if (escapedValue > 0x10FFFF) {
9271                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9272                 isInvalidExtendedEscape = true;
9273             }
9274             if (pos >= end) {
9275                 error(ts.Diagnostics.Unexpected_end_of_text);
9276                 isInvalidExtendedEscape = true;
9277             }
9278             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9279                 // Only swallow the following character up if it's a '}'.
9280                 pos++;
9281             }
9282             else {
9283                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9284                 isInvalidExtendedEscape = true;
9285             }
9286             if (isInvalidExtendedEscape) {
9287                 return "";
9288             }
9289             return utf16EncodeAsString(escapedValue);
9290         }
9291         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9292         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9293         function peekUnicodeEscape() {
9294             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9295                 var start_1 = pos;
9296                 pos += 2;
9297                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9298                 pos = start_1;
9299                 return value;
9300             }
9301             return -1;
9302         }
9303         function peekExtendedUnicodeEscape() {
9304             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9305                 var start_2 = pos;
9306                 pos += 3;
9307                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9308                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9309                 pos = start_2;
9310                 return escapedValue;
9311             }
9312             return -1;
9313         }
9314         function scanIdentifierParts() {
9315             var result = "";
9316             var start = pos;
9317             while (pos < end) {
9318                 var ch = codePointAt(text, pos);
9319                 if (isIdentifierPart(ch, languageVersion)) {
9320                     pos += charSize(ch);
9321                 }
9322                 else if (ch === 92 /* backslash */) {
9323                     ch = peekExtendedUnicodeEscape();
9324                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9325                         pos += 3;
9326                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9327                         result += scanExtendedUnicodeEscape();
9328                         start = pos;
9329                         continue;
9330                     }
9331                     ch = peekUnicodeEscape();
9332                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9333                         break;
9334                     }
9335                     tokenFlags |= 1024 /* UnicodeEscape */;
9336                     result += text.substring(start, pos);
9337                     result += utf16EncodeAsString(ch);
9338                     // Valid Unicode escape is always six characters
9339                     pos += 6;
9340                     start = pos;
9341                 }
9342                 else {
9343                     break;
9344                 }
9345             }
9346             result += text.substring(start, pos);
9347             return result;
9348         }
9349         function getIdentifierToken() {
9350             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9351             var len = tokenValue.length;
9352             if (len >= 2 && len <= 11) {
9353                 var ch = tokenValue.charCodeAt(0);
9354                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9355                     var keyword = textToKeyword.get(tokenValue);
9356                     if (keyword !== undefined) {
9357                         return token = keyword;
9358                     }
9359                 }
9360             }
9361             return token = 75 /* Identifier */;
9362         }
9363         function scanBinaryOrOctalDigits(base) {
9364             var value = "";
9365             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9366             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9367             var separatorAllowed = false;
9368             var isPreviousTokenSeparator = false;
9369             while (true) {
9370                 var ch = text.charCodeAt(pos);
9371                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9372                 if (ch === 95 /* _ */) {
9373                     tokenFlags |= 512 /* ContainsSeparator */;
9374                     if (separatorAllowed) {
9375                         separatorAllowed = false;
9376                         isPreviousTokenSeparator = true;
9377                     }
9378                     else if (isPreviousTokenSeparator) {
9379                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9380                     }
9381                     else {
9382                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9383                     }
9384                     pos++;
9385                     continue;
9386                 }
9387                 separatorAllowed = true;
9388                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9389                     break;
9390                 }
9391                 value += text[pos];
9392                 pos++;
9393                 isPreviousTokenSeparator = false;
9394             }
9395             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9396                 // Literal ends with underscore - not allowed
9397                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9398             }
9399             return value;
9400         }
9401         function checkBigIntSuffix() {
9402             if (text.charCodeAt(pos) === 110 /* n */) {
9403                 tokenValue += "n";
9404                 // Use base 10 instead of base 2 or base 8 for shorter literals
9405                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9406                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9407                 }
9408                 pos++;
9409                 return 9 /* BigIntLiteral */;
9410             }
9411             else { // not a bigint, so can convert to number in simplified form
9412                 // Number() may not support 0b or 0o, so use parseInt() instead
9413                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9414                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9415                     : tokenFlags & 256 /* OctalSpecifier */
9416                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9417                         : +tokenValue;
9418                 tokenValue = "" + numericValue;
9419                 return 8 /* NumericLiteral */;
9420             }
9421         }
9422         function scan() {
9423             var _a;
9424             startPos = pos;
9425             tokenFlags = 0 /* None */;
9426             var asteriskSeen = false;
9427             while (true) {
9428                 tokenPos = pos;
9429                 if (pos >= end) {
9430                     return token = 1 /* EndOfFileToken */;
9431                 }
9432                 var ch = codePointAt(text, pos);
9433                 // Special handling for shebang
9434                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9435                     pos = scanShebangTrivia(text, pos);
9436                     if (skipTrivia) {
9437                         continue;
9438                     }
9439                     else {
9440                         return token = 6 /* ShebangTrivia */;
9441                     }
9442                 }
9443                 switch (ch) {
9444                     case 10 /* lineFeed */:
9445                     case 13 /* carriageReturn */:
9446                         tokenFlags |= 1 /* PrecedingLineBreak */;
9447                         if (skipTrivia) {
9448                             pos++;
9449                             continue;
9450                         }
9451                         else {
9452                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9453                                 // consume both CR and LF
9454                                 pos += 2;
9455                             }
9456                             else {
9457                                 pos++;
9458                             }
9459                             return token = 4 /* NewLineTrivia */;
9460                         }
9461                     case 9 /* tab */:
9462                     case 11 /* verticalTab */:
9463                     case 12 /* formFeed */:
9464                     case 32 /* space */:
9465                     case 160 /* nonBreakingSpace */:
9466                     case 5760 /* ogham */:
9467                     case 8192 /* enQuad */:
9468                     case 8193 /* emQuad */:
9469                     case 8194 /* enSpace */:
9470                     case 8195 /* emSpace */:
9471                     case 8196 /* threePerEmSpace */:
9472                     case 8197 /* fourPerEmSpace */:
9473                     case 8198 /* sixPerEmSpace */:
9474                     case 8199 /* figureSpace */:
9475                     case 8200 /* punctuationSpace */:
9476                     case 8201 /* thinSpace */:
9477                     case 8202 /* hairSpace */:
9478                     case 8203 /* zeroWidthSpace */:
9479                     case 8239 /* narrowNoBreakSpace */:
9480                     case 8287 /* mathematicalSpace */:
9481                     case 12288 /* ideographicSpace */:
9482                     case 65279 /* byteOrderMark */:
9483                         if (skipTrivia) {
9484                             pos++;
9485                             continue;
9486                         }
9487                         else {
9488                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9489                                 pos++;
9490                             }
9491                             return token = 5 /* WhitespaceTrivia */;
9492                         }
9493                     case 33 /* exclamation */:
9494                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9495                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9496                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9497                             }
9498                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9499                         }
9500                         pos++;
9501                         return token = 53 /* ExclamationToken */;
9502                     case 34 /* doubleQuote */:
9503                     case 39 /* singleQuote */:
9504                         tokenValue = scanString();
9505                         return token = 10 /* StringLiteral */;
9506                     case 96 /* backtick */:
9507                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9508                     case 37 /* percent */:
9509                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9510                             return pos += 2, token = 68 /* PercentEqualsToken */;
9511                         }
9512                         pos++;
9513                         return token = 44 /* PercentToken */;
9514                     case 38 /* ampersand */:
9515                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9516                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9517                         }
9518                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9519                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9520                         }
9521                         pos++;
9522                         return token = 50 /* AmpersandToken */;
9523                     case 40 /* openParen */:
9524                         pos++;
9525                         return token = 20 /* OpenParenToken */;
9526                     case 41 /* closeParen */:
9527                         pos++;
9528                         return token = 21 /* CloseParenToken */;
9529                     case 42 /* asterisk */:
9530                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9531                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9532                         }
9533                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9534                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9535                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9536                             }
9537                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9538                         }
9539                         pos++;
9540                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9541                             // decoration at the start of a JSDoc comment line
9542                             asteriskSeen = true;
9543                             continue;
9544                         }
9545                         return token = 41 /* AsteriskToken */;
9546                     case 43 /* plus */:
9547                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9548                             return pos += 2, token = 45 /* PlusPlusToken */;
9549                         }
9550                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9551                             return pos += 2, token = 63 /* PlusEqualsToken */;
9552                         }
9553                         pos++;
9554                         return token = 39 /* PlusToken */;
9555                     case 44 /* comma */:
9556                         pos++;
9557                         return token = 27 /* CommaToken */;
9558                     case 45 /* minus */:
9559                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9560                             return pos += 2, token = 46 /* MinusMinusToken */;
9561                         }
9562                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9563                             return pos += 2, token = 64 /* MinusEqualsToken */;
9564                         }
9565                         pos++;
9566                         return token = 40 /* MinusToken */;
9567                     case 46 /* dot */:
9568                         if (isDigit(text.charCodeAt(pos + 1))) {
9569                             tokenValue = scanNumber().value;
9570                             return token = 8 /* NumericLiteral */;
9571                         }
9572                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9573                             return pos += 3, token = 25 /* DotDotDotToken */;
9574                         }
9575                         pos++;
9576                         return token = 24 /* DotToken */;
9577                     case 47 /* slash */:
9578                         // Single-line comment
9579                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9580                             pos += 2;
9581                             while (pos < end) {
9582                                 if (isLineBreak(text.charCodeAt(pos))) {
9583                                     break;
9584                                 }
9585                                 pos++;
9586                             }
9587                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9588                             if (skipTrivia) {
9589                                 continue;
9590                             }
9591                             else {
9592                                 return token = 2 /* SingleLineCommentTrivia */;
9593                             }
9594                         }
9595                         // Multi-line comment
9596                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9597                             pos += 2;
9598                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9599                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9600                             }
9601                             var commentClosed = false;
9602                             var lastLineStart = tokenPos;
9603                             while (pos < end) {
9604                                 var ch_1 = text.charCodeAt(pos);
9605                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9606                                     pos += 2;
9607                                     commentClosed = true;
9608                                     break;
9609                                 }
9610                                 pos++;
9611                                 if (isLineBreak(ch_1)) {
9612                                     lastLineStart = pos;
9613                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9614                                 }
9615                             }
9616                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9617                             if (!commentClosed) {
9618                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9619                             }
9620                             if (skipTrivia) {
9621                                 continue;
9622                             }
9623                             else {
9624                                 if (!commentClosed) {
9625                                     tokenFlags |= 4 /* Unterminated */;
9626                                 }
9627                                 return token = 3 /* MultiLineCommentTrivia */;
9628                             }
9629                         }
9630                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9631                             return pos += 2, token = 67 /* SlashEqualsToken */;
9632                         }
9633                         pos++;
9634                         return token = 43 /* SlashToken */;
9635                     case 48 /* _0 */:
9636                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9637                             pos += 2;
9638                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9639                             if (!tokenValue) {
9640                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9641                                 tokenValue = "0";
9642                             }
9643                             tokenValue = "0x" + tokenValue;
9644                             tokenFlags |= 64 /* HexSpecifier */;
9645                             return token = checkBigIntSuffix();
9646                         }
9647                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9648                             pos += 2;
9649                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9650                             if (!tokenValue) {
9651                                 error(ts.Diagnostics.Binary_digit_expected);
9652                                 tokenValue = "0";
9653                             }
9654                             tokenValue = "0b" + tokenValue;
9655                             tokenFlags |= 128 /* BinarySpecifier */;
9656                             return token = checkBigIntSuffix();
9657                         }
9658                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9659                             pos += 2;
9660                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9661                             if (!tokenValue) {
9662                                 error(ts.Diagnostics.Octal_digit_expected);
9663                                 tokenValue = "0";
9664                             }
9665                             tokenValue = "0o" + tokenValue;
9666                             tokenFlags |= 256 /* OctalSpecifier */;
9667                             return token = checkBigIntSuffix();
9668                         }
9669                         // Try to parse as an octal
9670                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9671                             tokenValue = "" + scanOctalDigits();
9672                             tokenFlags |= 32 /* Octal */;
9673                             return token = 8 /* NumericLiteral */;
9674                         }
9675                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9676                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9677                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9678                     // falls through
9679                     case 49 /* _1 */:
9680                     case 50 /* _2 */:
9681                     case 51 /* _3 */:
9682                     case 52 /* _4 */:
9683                     case 53 /* _5 */:
9684                     case 54 /* _6 */:
9685                     case 55 /* _7 */:
9686                     case 56 /* _8 */:
9687                     case 57 /* _9 */:
9688                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9689                         return token;
9690                     case 58 /* colon */:
9691                         pos++;
9692                         return token = 58 /* ColonToken */;
9693                     case 59 /* semicolon */:
9694                         pos++;
9695                         return token = 26 /* SemicolonToken */;
9696                     case 60 /* lessThan */:
9697                         if (isConflictMarkerTrivia(text, pos)) {
9698                             pos = scanConflictMarkerTrivia(text, pos, error);
9699                             if (skipTrivia) {
9700                                 continue;
9701                             }
9702                             else {
9703                                 return token = 7 /* ConflictMarkerTrivia */;
9704                             }
9705                         }
9706                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9707                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9708                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9709                             }
9710                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9711                         }
9712                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9713                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9714                         }
9715                         if (languageVariant === 1 /* JSX */ &&
9716                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9717                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9718                             return pos += 2, token = 30 /* LessThanSlashToken */;
9719                         }
9720                         pos++;
9721                         return token = 29 /* LessThanToken */;
9722                     case 61 /* equals */:
9723                         if (isConflictMarkerTrivia(text, pos)) {
9724                             pos = scanConflictMarkerTrivia(text, pos, error);
9725                             if (skipTrivia) {
9726                                 continue;
9727                             }
9728                             else {
9729                                 return token = 7 /* ConflictMarkerTrivia */;
9730                             }
9731                         }
9732                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9733                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9734                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9735                             }
9736                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9737                         }
9738                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9739                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9740                         }
9741                         pos++;
9742                         return token = 62 /* EqualsToken */;
9743                     case 62 /* greaterThan */:
9744                         if (isConflictMarkerTrivia(text, pos)) {
9745                             pos = scanConflictMarkerTrivia(text, pos, error);
9746                             if (skipTrivia) {
9747                                 continue;
9748                             }
9749                             else {
9750                                 return token = 7 /* ConflictMarkerTrivia */;
9751                             }
9752                         }
9753                         pos++;
9754                         return token = 31 /* GreaterThanToken */;
9755                     case 63 /* question */:
9756                         pos++;
9757                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9758                             pos++;
9759                             return token = 28 /* QuestionDotToken */;
9760                         }
9761                         if (text.charCodeAt(pos) === 63 /* question */) {
9762                             pos++;
9763                             return token = 60 /* QuestionQuestionToken */;
9764                         }
9765                         return token = 57 /* QuestionToken */;
9766                     case 91 /* openBracket */:
9767                         pos++;
9768                         return token = 22 /* OpenBracketToken */;
9769                     case 93 /* closeBracket */:
9770                         pos++;
9771                         return token = 23 /* CloseBracketToken */;
9772                     case 94 /* caret */:
9773                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9774                             return pos += 2, token = 74 /* CaretEqualsToken */;
9775                         }
9776                         pos++;
9777                         return token = 52 /* CaretToken */;
9778                     case 123 /* openBrace */:
9779                         pos++;
9780                         return token = 18 /* OpenBraceToken */;
9781                     case 124 /* bar */:
9782                         if (isConflictMarkerTrivia(text, pos)) {
9783                             pos = scanConflictMarkerTrivia(text, pos, error);
9784                             if (skipTrivia) {
9785                                 continue;
9786                             }
9787                             else {
9788                                 return token = 7 /* ConflictMarkerTrivia */;
9789                             }
9790                         }
9791                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9792                             return pos += 2, token = 56 /* BarBarToken */;
9793                         }
9794                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9795                             return pos += 2, token = 73 /* BarEqualsToken */;
9796                         }
9797                         pos++;
9798                         return token = 51 /* BarToken */;
9799                     case 125 /* closeBrace */:
9800                         pos++;
9801                         return token = 19 /* CloseBraceToken */;
9802                     case 126 /* tilde */:
9803                         pos++;
9804                         return token = 54 /* TildeToken */;
9805                     case 64 /* at */:
9806                         pos++;
9807                         return token = 59 /* AtToken */;
9808                     case 92 /* backslash */:
9809                         var extendedCookedChar = peekExtendedUnicodeEscape();
9810                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9811                             pos += 3;
9812                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9813                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9814                             return token = getIdentifierToken();
9815                         }
9816                         var cookedChar = peekUnicodeEscape();
9817                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9818                             pos += 6;
9819                             tokenFlags |= 1024 /* UnicodeEscape */;
9820                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9821                             return token = getIdentifierToken();
9822                         }
9823                         error(ts.Diagnostics.Invalid_character);
9824                         pos++;
9825                         return token = 0 /* Unknown */;
9826                     case 35 /* hash */:
9827                         if (pos !== 0 && text[pos + 1] === "!") {
9828                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9829                             pos++;
9830                             return token = 0 /* Unknown */;
9831                         }
9832                         pos++;
9833                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9834                             pos++;
9835                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9836                                 pos++;
9837                             tokenValue = text.substring(tokenPos, pos);
9838                             if (ch === 92 /* backslash */) {
9839                                 tokenValue += scanIdentifierParts();
9840                             }
9841                         }
9842                         else {
9843                             tokenValue = "#";
9844                             error(ts.Diagnostics.Invalid_character);
9845                         }
9846                         return token = 76 /* PrivateIdentifier */;
9847                     default:
9848                         if (isIdentifierStart(ch, languageVersion)) {
9849                             pos += charSize(ch);
9850                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
9851                                 pos += charSize(ch);
9852                             tokenValue = text.substring(tokenPos, pos);
9853                             if (ch === 92 /* backslash */) {
9854                                 tokenValue += scanIdentifierParts();
9855                             }
9856                             return token = getIdentifierToken();
9857                         }
9858                         else if (isWhiteSpaceSingleLine(ch)) {
9859                             pos += charSize(ch);
9860                             continue;
9861                         }
9862                         else if (isLineBreak(ch)) {
9863                             tokenFlags |= 1 /* PrecedingLineBreak */;
9864                             pos += charSize(ch);
9865                             continue;
9866                         }
9867                         error(ts.Diagnostics.Invalid_character);
9868                         pos += charSize(ch);
9869                         return token = 0 /* Unknown */;
9870                 }
9871             }
9872         }
9873         function reScanGreaterToken() {
9874             if (token === 31 /* GreaterThanToken */) {
9875                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
9876                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9877                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9878                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
9879                         }
9880                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
9881                     }
9882                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9883                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
9884                     }
9885                     pos++;
9886                     return token = 48 /* GreaterThanGreaterThanToken */;
9887                 }
9888                 if (text.charCodeAt(pos) === 61 /* equals */) {
9889                     pos++;
9890                     return token = 33 /* GreaterThanEqualsToken */;
9891                 }
9892             }
9893             return token;
9894         }
9895         function reScanSlashToken() {
9896             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
9897                 var p = tokenPos + 1;
9898                 var inEscape = false;
9899                 var inCharacterClass = false;
9900                 while (true) {
9901                     // If we reach the end of a file, or hit a newline, then this is an unterminated
9902                     // regex.  Report error and return what we have so far.
9903                     if (p >= end) {
9904                         tokenFlags |= 4 /* Unterminated */;
9905                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9906                         break;
9907                     }
9908                     var ch = text.charCodeAt(p);
9909                     if (isLineBreak(ch)) {
9910                         tokenFlags |= 4 /* Unterminated */;
9911                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9912                         break;
9913                     }
9914                     if (inEscape) {
9915                         // Parsing an escape character;
9916                         // reset the flag and just advance to the next char.
9917                         inEscape = false;
9918                     }
9919                     else if (ch === 47 /* slash */ && !inCharacterClass) {
9920                         // A slash within a character class is permissible,
9921                         // but in general it signals the end of the regexp literal.
9922                         p++;
9923                         break;
9924                     }
9925                     else if (ch === 91 /* openBracket */) {
9926                         inCharacterClass = true;
9927                     }
9928                     else if (ch === 92 /* backslash */) {
9929                         inEscape = true;
9930                     }
9931                     else if (ch === 93 /* closeBracket */) {
9932                         inCharacterClass = false;
9933                     }
9934                     p++;
9935                 }
9936                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
9937                     p++;
9938                 }
9939                 pos = p;
9940                 tokenValue = text.substring(tokenPos, pos);
9941                 token = 13 /* RegularExpressionLiteral */;
9942             }
9943             return token;
9944         }
9945         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
9946             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
9947             if (type === undefined) {
9948                 return commentDirectives;
9949             }
9950             return ts.append(commentDirectives, {
9951                 range: { pos: lineStart, end: pos },
9952                 type: type,
9953             });
9954         }
9955         function getDirectiveFromComment(text, commentDirectiveRegEx) {
9956             var match = commentDirectiveRegEx.exec(text);
9957             if (!match) {
9958                 return undefined;
9959             }
9960             switch (match[1]) {
9961                 case "ts-expect-error":
9962                     return 0 /* ExpectError */;
9963                 case "ts-ignore":
9964                     return 1 /* Ignore */;
9965             }
9966             return undefined;
9967         }
9968         /**
9969          * Unconditionally back up and scan a template expression portion.
9970          */
9971         function reScanTemplateToken(isTaggedTemplate) {
9972             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
9973             pos = tokenPos;
9974             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
9975         }
9976         function reScanTemplateHeadOrNoSubstitutionTemplate() {
9977             pos = tokenPos;
9978             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
9979         }
9980         function reScanJsxToken() {
9981             pos = tokenPos = startPos;
9982             return token = scanJsxToken();
9983         }
9984         function reScanLessThanToken() {
9985             if (token === 47 /* LessThanLessThanToken */) {
9986                 pos = tokenPos + 1;
9987                 return token = 29 /* LessThanToken */;
9988             }
9989             return token;
9990         }
9991         function reScanQuestionToken() {
9992             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
9993             pos = tokenPos + 1;
9994             return token = 57 /* QuestionToken */;
9995         }
9996         function scanJsxToken() {
9997             startPos = tokenPos = pos;
9998             if (pos >= end) {
9999                 return token = 1 /* EndOfFileToken */;
10000             }
10001             var char = text.charCodeAt(pos);
10002             if (char === 60 /* lessThan */) {
10003                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10004                     pos += 2;
10005                     return token = 30 /* LessThanSlashToken */;
10006                 }
10007                 pos++;
10008                 return token = 29 /* LessThanToken */;
10009             }
10010             if (char === 123 /* openBrace */) {
10011                 pos++;
10012                 return token = 18 /* OpenBraceToken */;
10013             }
10014             // First non-whitespace character on this line.
10015             var firstNonWhitespace = 0;
10016             var lastNonWhitespace = -1;
10017             // These initial values are special because the first line is:
10018             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10019             while (pos < end) {
10020                 // We want to keep track of the last non-whitespace (but including
10021                 // newlines character for hitting the end of the JSX Text region)
10022                 if (!isWhiteSpaceSingleLine(char)) {
10023                     lastNonWhitespace = pos;
10024                 }
10025                 char = text.charCodeAt(pos);
10026                 if (char === 123 /* openBrace */) {
10027                     break;
10028                 }
10029                 if (char === 60 /* lessThan */) {
10030                     if (isConflictMarkerTrivia(text, pos)) {
10031                         pos = scanConflictMarkerTrivia(text, pos, error);
10032                         return token = 7 /* ConflictMarkerTrivia */;
10033                     }
10034                     break;
10035                 }
10036                 if (char === 62 /* greaterThan */) {
10037                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10038                 }
10039                 if (char === 125 /* closeBrace */) {
10040                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10041                 }
10042                 if (lastNonWhitespace > 0)
10043                     lastNonWhitespace++;
10044                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10045                 // i.e (- : whitespace)
10046                 //      <div>----
10047                 //      </div> becomes <div></div>
10048                 //
10049                 //      <div>----</div> becomes <div>----</div>
10050                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10051                     firstNonWhitespace = -1;
10052                 }
10053                 else if (!isWhiteSpaceLike(char)) {
10054                     firstNonWhitespace = pos;
10055                 }
10056                 pos++;
10057             }
10058             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10059             tokenValue = text.substring(startPos, endPosition);
10060             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10061         }
10062         // Scans a JSX identifier; these differ from normal identifiers in that
10063         // they allow dashes
10064         function scanJsxIdentifier() {
10065             if (tokenIsIdentifierOrKeyword(token)) {
10066                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10067                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10068                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10069                 while (pos < end) {
10070                     var ch = text.charCodeAt(pos);
10071                     if (ch === 45 /* minus */) {
10072                         tokenValue += "-";
10073                         pos++;
10074                         continue;
10075                     }
10076                     var oldPos = pos;
10077                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10078                     if (pos === oldPos) {
10079                         break;
10080                     }
10081                 }
10082             }
10083             return token;
10084         }
10085         function scanJsxAttributeValue() {
10086             startPos = pos;
10087             switch (text.charCodeAt(pos)) {
10088                 case 34 /* doubleQuote */:
10089                 case 39 /* singleQuote */:
10090                     tokenValue = scanString(/*jsxAttributeString*/ true);
10091                     return token = 10 /* StringLiteral */;
10092                 default:
10093                     // If this scans anything other than `{`, it's a parse error.
10094                     return scan();
10095             }
10096         }
10097         function reScanJsxAttributeValue() {
10098             pos = tokenPos = startPos;
10099             return scanJsxAttributeValue();
10100         }
10101         function scanJsDocToken() {
10102             startPos = tokenPos = pos;
10103             tokenFlags = 0 /* None */;
10104             if (pos >= end) {
10105                 return token = 1 /* EndOfFileToken */;
10106             }
10107             var ch = codePointAt(text, pos);
10108             pos += charSize(ch);
10109             switch (ch) {
10110                 case 9 /* tab */:
10111                 case 11 /* verticalTab */:
10112                 case 12 /* formFeed */:
10113                 case 32 /* space */:
10114                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10115                         pos++;
10116                     }
10117                     return token = 5 /* WhitespaceTrivia */;
10118                 case 64 /* at */:
10119                     return token = 59 /* AtToken */;
10120                 case 10 /* lineFeed */:
10121                 case 13 /* carriageReturn */:
10122                     tokenFlags |= 1 /* PrecedingLineBreak */;
10123                     return token = 4 /* NewLineTrivia */;
10124                 case 42 /* asterisk */:
10125                     return token = 41 /* AsteriskToken */;
10126                 case 123 /* openBrace */:
10127                     return token = 18 /* OpenBraceToken */;
10128                 case 125 /* closeBrace */:
10129                     return token = 19 /* CloseBraceToken */;
10130                 case 91 /* openBracket */:
10131                     return token = 22 /* OpenBracketToken */;
10132                 case 93 /* closeBracket */:
10133                     return token = 23 /* CloseBracketToken */;
10134                 case 60 /* lessThan */:
10135                     return token = 29 /* LessThanToken */;
10136                 case 62 /* greaterThan */:
10137                     return token = 31 /* GreaterThanToken */;
10138                 case 61 /* equals */:
10139                     return token = 62 /* EqualsToken */;
10140                 case 44 /* comma */:
10141                     return token = 27 /* CommaToken */;
10142                 case 46 /* dot */:
10143                     return token = 24 /* DotToken */;
10144                 case 96 /* backtick */:
10145                     return token = 61 /* BacktickToken */;
10146                 case 92 /* backslash */:
10147                     pos--;
10148                     var extendedCookedChar = peekExtendedUnicodeEscape();
10149                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10150                         pos += 3;
10151                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10152                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10153                         return token = getIdentifierToken();
10154                     }
10155                     var cookedChar = peekUnicodeEscape();
10156                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10157                         pos += 6;
10158                         tokenFlags |= 1024 /* UnicodeEscape */;
10159                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10160                         return token = getIdentifierToken();
10161                     }
10162                     pos++;
10163                     return token = 0 /* Unknown */;
10164             }
10165             if (isIdentifierStart(ch, languageVersion)) {
10166                 var char = ch;
10167                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10168                     pos += charSize(char);
10169                 tokenValue = text.substring(tokenPos, pos);
10170                 if (char === 92 /* backslash */) {
10171                     tokenValue += scanIdentifierParts();
10172                 }
10173                 return token = getIdentifierToken();
10174             }
10175             else {
10176                 return token = 0 /* Unknown */;
10177             }
10178         }
10179         function speculationHelper(callback, isLookahead) {
10180             var savePos = pos;
10181             var saveStartPos = startPos;
10182             var saveTokenPos = tokenPos;
10183             var saveToken = token;
10184             var saveTokenValue = tokenValue;
10185             var saveTokenFlags = tokenFlags;
10186             var result = callback();
10187             // If our callback returned something 'falsy' or we're just looking ahead,
10188             // then unconditionally restore us to where we were.
10189             if (!result || isLookahead) {
10190                 pos = savePos;
10191                 startPos = saveStartPos;
10192                 tokenPos = saveTokenPos;
10193                 token = saveToken;
10194                 tokenValue = saveTokenValue;
10195                 tokenFlags = saveTokenFlags;
10196             }
10197             return result;
10198         }
10199         function scanRange(start, length, callback) {
10200             var saveEnd = end;
10201             var savePos = pos;
10202             var saveStartPos = startPos;
10203             var saveTokenPos = tokenPos;
10204             var saveToken = token;
10205             var saveTokenValue = tokenValue;
10206             var saveTokenFlags = tokenFlags;
10207             var saveErrorExpectations = commentDirectives;
10208             setText(text, start, length);
10209             var result = callback();
10210             end = saveEnd;
10211             pos = savePos;
10212             startPos = saveStartPos;
10213             tokenPos = saveTokenPos;
10214             token = saveToken;
10215             tokenValue = saveTokenValue;
10216             tokenFlags = saveTokenFlags;
10217             commentDirectives = saveErrorExpectations;
10218             return result;
10219         }
10220         function lookAhead(callback) {
10221             return speculationHelper(callback, /*isLookahead*/ true);
10222         }
10223         function tryScan(callback) {
10224             return speculationHelper(callback, /*isLookahead*/ false);
10225         }
10226         function getText() {
10227             return text;
10228         }
10229         function clearCommentDirectives() {
10230             commentDirectives = undefined;
10231         }
10232         function setText(newText, start, length) {
10233             text = newText || "";
10234             end = length === undefined ? text.length : start + length;
10235             setTextPos(start || 0);
10236         }
10237         function setOnError(errorCallback) {
10238             onError = errorCallback;
10239         }
10240         function setScriptTarget(scriptTarget) {
10241             languageVersion = scriptTarget;
10242         }
10243         function setLanguageVariant(variant) {
10244             languageVariant = variant;
10245         }
10246         function setTextPos(textPos) {
10247             ts.Debug.assert(textPos >= 0);
10248             pos = textPos;
10249             startPos = textPos;
10250             tokenPos = textPos;
10251             token = 0 /* Unknown */;
10252             tokenValue = undefined;
10253             tokenFlags = 0 /* None */;
10254         }
10255         function setInJSDocType(inType) {
10256             inJSDocType += inType ? 1 : -1;
10257         }
10258     }
10259     ts.createScanner = createScanner;
10260     /* @internal */
10261     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10262         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10263         var size = str.length;
10264         // Account for out-of-bounds indices:
10265         if (i < 0 || i >= size) {
10266             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10267         }
10268         // Get the first code unit
10269         var first = str.charCodeAt(i);
10270         // check if it’s the start of a surrogate pair
10271         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10272             var second = str.charCodeAt(i + 1);
10273             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10274                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10275                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10276             }
10277         }
10278         return first;
10279     };
10280     /* @internal */
10281     function charSize(ch) {
10282         if (ch >= 0x10000) {
10283             return 2;
10284         }
10285         return 1;
10286     }
10287     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10288     function utf16EncodeAsStringFallback(codePoint) {
10289         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10290         if (codePoint <= 65535) {
10291             return String.fromCharCode(codePoint);
10292         }
10293         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10294         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10295         return String.fromCharCode(codeUnit1, codeUnit2);
10296     }
10297     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10298     /* @internal */
10299     function utf16EncodeAsString(codePoint) {
10300         return utf16EncodeAsStringWorker(codePoint);
10301     }
10302     ts.utf16EncodeAsString = utf16EncodeAsString;
10303 })(ts || (ts = {}));
10304 var ts;
10305 (function (ts) {
10306     function isExternalModuleNameRelative(moduleName) {
10307         // TypeScript 1.0 spec (April 2014): 11.2.1
10308         // An external module name is "relative" if the first term is "." or "..".
10309         // 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.
10310         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10311     }
10312     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10313     function sortAndDeduplicateDiagnostics(diagnostics) {
10314         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10315     }
10316     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10317     function getDefaultLibFileName(options) {
10318         switch (options.target) {
10319             case 99 /* ESNext */:
10320                 return "lib.esnext.full.d.ts";
10321             case 7 /* ES2020 */:
10322                 return "lib.es2020.full.d.ts";
10323             case 6 /* ES2019 */:
10324                 return "lib.es2019.full.d.ts";
10325             case 5 /* ES2018 */:
10326                 return "lib.es2018.full.d.ts";
10327             case 4 /* ES2017 */:
10328                 return "lib.es2017.full.d.ts";
10329             case 3 /* ES2016 */:
10330                 return "lib.es2016.full.d.ts";
10331             case 2 /* ES2015 */:
10332                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10333             default:
10334                 return "lib.d.ts";
10335         }
10336     }
10337     ts.getDefaultLibFileName = getDefaultLibFileName;
10338     function textSpanEnd(span) {
10339         return span.start + span.length;
10340     }
10341     ts.textSpanEnd = textSpanEnd;
10342     function textSpanIsEmpty(span) {
10343         return span.length === 0;
10344     }
10345     ts.textSpanIsEmpty = textSpanIsEmpty;
10346     function textSpanContainsPosition(span, position) {
10347         return position >= span.start && position < textSpanEnd(span);
10348     }
10349     ts.textSpanContainsPosition = textSpanContainsPosition;
10350     /* @internal */
10351     function textRangeContainsPositionInclusive(span, position) {
10352         return position >= span.pos && position <= span.end;
10353     }
10354     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10355     // Returns true if 'span' contains 'other'.
10356     function textSpanContainsTextSpan(span, other) {
10357         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10358     }
10359     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10360     function textSpanOverlapsWith(span, other) {
10361         return textSpanOverlap(span, other) !== undefined;
10362     }
10363     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10364     function textSpanOverlap(span1, span2) {
10365         var overlap = textSpanIntersection(span1, span2);
10366         return overlap && overlap.length === 0 ? undefined : overlap;
10367     }
10368     ts.textSpanOverlap = textSpanOverlap;
10369     function textSpanIntersectsWithTextSpan(span, other) {
10370         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10371     }
10372     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10373     function textSpanIntersectsWith(span, start, length) {
10374         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10375     }
10376     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10377     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10378         var end1 = start1 + length1;
10379         var end2 = start2 + length2;
10380         return start2 <= end1 && end2 >= start1;
10381     }
10382     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10383     function textSpanIntersectsWithPosition(span, position) {
10384         return position <= textSpanEnd(span) && position >= span.start;
10385     }
10386     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10387     function textSpanIntersection(span1, span2) {
10388         var start = Math.max(span1.start, span2.start);
10389         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10390         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10391     }
10392     ts.textSpanIntersection = textSpanIntersection;
10393     function createTextSpan(start, length) {
10394         if (start < 0) {
10395             throw new Error("start < 0");
10396         }
10397         if (length < 0) {
10398             throw new Error("length < 0");
10399         }
10400         return { start: start, length: length };
10401     }
10402     ts.createTextSpan = createTextSpan;
10403     function createTextSpanFromBounds(start, end) {
10404         return createTextSpan(start, end - start);
10405     }
10406     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10407     function textChangeRangeNewSpan(range) {
10408         return createTextSpan(range.span.start, range.newLength);
10409     }
10410     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10411     function textChangeRangeIsUnchanged(range) {
10412         return textSpanIsEmpty(range.span) && range.newLength === 0;
10413     }
10414     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10415     function createTextChangeRange(span, newLength) {
10416         if (newLength < 0) {
10417             throw new Error("newLength < 0");
10418         }
10419         return { span: span, newLength: newLength };
10420     }
10421     ts.createTextChangeRange = createTextChangeRange;
10422     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10423     /**
10424      * Called to merge all the changes that occurred across several versions of a script snapshot
10425      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10426      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10427      *
10428      * This function will then merge those changes into a single change range valid between V1 and
10429      * Vn.
10430      */
10431     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10432         if (changes.length === 0) {
10433             return ts.unchangedTextChangeRange;
10434         }
10435         if (changes.length === 1) {
10436             return changes[0];
10437         }
10438         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10439         // as it makes things much easier to reason about.
10440         var change0 = changes[0];
10441         var oldStartN = change0.span.start;
10442         var oldEndN = textSpanEnd(change0.span);
10443         var newEndN = oldStartN + change0.newLength;
10444         for (var i = 1; i < changes.length; i++) {
10445             var nextChange = changes[i];
10446             // Consider the following case:
10447             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10448             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10449             // i.e. the span starting at 30 with length 30 is increased to length 40.
10450             //
10451             //      0         10        20        30        40        50        60        70        80        90        100
10452             //      -------------------------------------------------------------------------------------------------------
10453             //                |                                                 /
10454             //                |                                            /----
10455             //  T1            |                                       /----
10456             //                |                                  /----
10457             //                |                             /----
10458             //      -------------------------------------------------------------------------------------------------------
10459             //                                     |                            \
10460             //                                     |                               \
10461             //   T2                                |                                 \
10462             //                                     |                                   \
10463             //                                     |                                      \
10464             //      -------------------------------------------------------------------------------------------------------
10465             //
10466             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10467             // it's just the min of the old and new starts.  i.e.:
10468             //
10469             //      0         10        20        30        40        50        60        70        80        90        100
10470             //      ------------------------------------------------------------*------------------------------------------
10471             //                |                                                 /
10472             //                |                                            /----
10473             //  T1            |                                       /----
10474             //                |                                  /----
10475             //                |                             /----
10476             //      ----------------------------------------$-------------------$------------------------------------------
10477             //                .                    |                            \
10478             //                .                    |                               \
10479             //   T2           .                    |                                 \
10480             //                .                    |                                   \
10481             //                .                    |                                      \
10482             //      ----------------------------------------------------------------------*--------------------------------
10483             //
10484             // (Note the dots represent the newly inferred start.
10485             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10486             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10487             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10488             // means:
10489             //
10490             //      0         10        20        30        40        50        60        70        80        90        100
10491             //      --------------------------------------------------------------------------------*----------------------
10492             //                |                                                                     /
10493             //                |                                                                /----
10494             //  T1            |                                                           /----
10495             //                |                                                      /----
10496             //                |                                                 /----
10497             //      ------------------------------------------------------------$------------------------------------------
10498             //                .                    |                            \
10499             //                .                    |                               \
10500             //   T2           .                    |                                 \
10501             //                .                    |                                   \
10502             //                .                    |                                      \
10503             //      ----------------------------------------------------------------------*--------------------------------
10504             //
10505             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10506             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10507             // that's the same as if we started at char 80 instead of 60.
10508             //
10509             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10510             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10511             // first.
10512             //
10513             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10514             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10515             //
10516             // The math then works out as follows.
10517             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10518             // final result like so:
10519             //
10520             // {
10521             //      oldStart3: Min(oldStart1, oldStart2),
10522             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10523             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10524             // }
10525             var oldStart1 = oldStartN;
10526             var oldEnd1 = oldEndN;
10527             var newEnd1 = newEndN;
10528             var oldStart2 = nextChange.span.start;
10529             var oldEnd2 = textSpanEnd(nextChange.span);
10530             var newEnd2 = oldStart2 + nextChange.newLength;
10531             oldStartN = Math.min(oldStart1, oldStart2);
10532             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10533             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10534         }
10535         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10536     }
10537     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10538     function getTypeParameterOwner(d) {
10539         if (d && d.kind === 155 /* TypeParameter */) {
10540             for (var current = d; current; current = current.parent) {
10541                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10542                     return current;
10543                 }
10544             }
10545         }
10546     }
10547     ts.getTypeParameterOwner = getTypeParameterOwner;
10548     function isParameterPropertyDeclaration(node, parent) {
10549         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10550     }
10551     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10552     function isEmptyBindingPattern(node) {
10553         if (isBindingPattern(node)) {
10554             return ts.every(node.elements, isEmptyBindingElement);
10555         }
10556         return false;
10557     }
10558     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10559     function isEmptyBindingElement(node) {
10560         if (isOmittedExpression(node)) {
10561             return true;
10562         }
10563         return isEmptyBindingPattern(node.name);
10564     }
10565     ts.isEmptyBindingElement = isEmptyBindingElement;
10566     function walkUpBindingElementsAndPatterns(binding) {
10567         var node = binding.parent;
10568         while (isBindingElement(node.parent)) {
10569             node = node.parent.parent;
10570         }
10571         return node.parent;
10572     }
10573     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10574     function getCombinedFlags(node, getFlags) {
10575         if (isBindingElement(node)) {
10576             node = walkUpBindingElementsAndPatterns(node);
10577         }
10578         var flags = getFlags(node);
10579         if (node.kind === 242 /* VariableDeclaration */) {
10580             node = node.parent;
10581         }
10582         if (node && node.kind === 243 /* VariableDeclarationList */) {
10583             flags |= getFlags(node);
10584             node = node.parent;
10585         }
10586         if (node && node.kind === 225 /* VariableStatement */) {
10587             flags |= getFlags(node);
10588         }
10589         return flags;
10590     }
10591     function getCombinedModifierFlags(node) {
10592         return getCombinedFlags(node, ts.getModifierFlags);
10593     }
10594     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10595     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10596     // nodes like variable declarations and binding elements can returned a view of their flags
10597     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10598     // stored on the variable declaration directly, but on the containing variable statement
10599     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10600     // list.  By calling this function, all those flags are combined so that the client can treat
10601     // the node as if it actually had those flags.
10602     function getCombinedNodeFlags(node) {
10603         return getCombinedFlags(node, function (n) { return n.flags; });
10604     }
10605     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10606     /**
10607      * Checks to see if the locale is in the appropriate format,
10608      * and if it is, attempts to set the appropriate language.
10609      */
10610     function validateLocaleAndSetLanguage(locale, sys, errors) {
10611         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10612         if (!matchResult) {
10613             if (errors) {
10614                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10615             }
10616             return;
10617         }
10618         var language = matchResult[1];
10619         var territory = matchResult[3];
10620         // First try the entire locale, then fall back to just language if that's all we have.
10621         // Either ways do not fail, and fallback to the English diagnostic strings.
10622         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10623             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10624         }
10625         // Set the UI locale for string collation
10626         ts.setUILocale(locale);
10627         function trySetLanguageAndTerritory(language, territory, errors) {
10628             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10629             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10630             var filePath = ts.combinePaths(containingDirectoryPath, language);
10631             if (territory) {
10632                 filePath = filePath + "-" + territory;
10633             }
10634             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10635             if (!sys.fileExists(filePath)) {
10636                 return false;
10637             }
10638             // TODO: Add codePage support for readFile?
10639             var fileContents = "";
10640             try {
10641                 fileContents = sys.readFile(filePath);
10642             }
10643             catch (e) {
10644                 if (errors) {
10645                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10646                 }
10647                 return false;
10648             }
10649             try {
10650                 // this is a global mutation (or live binding update)!
10651                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10652             }
10653             catch (_a) {
10654                 if (errors) {
10655                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10656                 }
10657                 return false;
10658             }
10659             return true;
10660         }
10661     }
10662     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10663     function getOriginalNode(node, nodeTest) {
10664         if (node) {
10665             while (node.original !== undefined) {
10666                 node = node.original;
10667             }
10668         }
10669         return !nodeTest || nodeTest(node) ? node : undefined;
10670     }
10671     ts.getOriginalNode = getOriginalNode;
10672     /**
10673      * Gets a value indicating whether a node originated in the parse tree.
10674      *
10675      * @param node The node to test.
10676      */
10677     function isParseTreeNode(node) {
10678         return (node.flags & 8 /* Synthesized */) === 0;
10679     }
10680     ts.isParseTreeNode = isParseTreeNode;
10681     function getParseTreeNode(node, nodeTest) {
10682         if (node === undefined || isParseTreeNode(node)) {
10683             return node;
10684         }
10685         node = getOriginalNode(node);
10686         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10687             return node;
10688         }
10689         return undefined;
10690     }
10691     ts.getParseTreeNode = getParseTreeNode;
10692     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10693     function escapeLeadingUnderscores(identifier) {
10694         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10695     }
10696     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10697     /**
10698      * Remove extra underscore from escaped identifier text content.
10699      *
10700      * @param identifier The escaped identifier text.
10701      * @returns The unescaped identifier text.
10702      */
10703     function unescapeLeadingUnderscores(identifier) {
10704         var id = identifier;
10705         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10706     }
10707     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10708     function idText(identifierOrPrivateName) {
10709         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10710     }
10711     ts.idText = idText;
10712     function symbolName(symbol) {
10713         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10714             return idText(symbol.valueDeclaration.name);
10715         }
10716         return unescapeLeadingUnderscores(symbol.escapedName);
10717     }
10718     ts.symbolName = symbolName;
10719     /**
10720      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10721      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10722      * will be merged with)
10723      */
10724     function nameForNamelessJSDocTypedef(declaration) {
10725         var hostNode = declaration.parent.parent;
10726         if (!hostNode) {
10727             return undefined;
10728         }
10729         // Covers classes, functions - any named declaration host node
10730         if (isDeclaration(hostNode)) {
10731             return getDeclarationIdentifier(hostNode);
10732         }
10733         // Covers remaining cases (returning undefined if none match).
10734         switch (hostNode.kind) {
10735             case 225 /* VariableStatement */:
10736                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10737                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10738                 }
10739                 break;
10740             case 226 /* ExpressionStatement */:
10741                 var expr = hostNode.expression;
10742                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10743                     expr = expr.left;
10744                 }
10745                 switch (expr.kind) {
10746                     case 194 /* PropertyAccessExpression */:
10747                         return expr.name;
10748                     case 195 /* ElementAccessExpression */:
10749                         var arg = expr.argumentExpression;
10750                         if (isIdentifier(arg)) {
10751                             return arg;
10752                         }
10753                 }
10754                 break;
10755             case 200 /* ParenthesizedExpression */: {
10756                 return getDeclarationIdentifier(hostNode.expression);
10757             }
10758             case 238 /* LabeledStatement */: {
10759                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10760                     return getDeclarationIdentifier(hostNode.statement);
10761                 }
10762                 break;
10763             }
10764         }
10765     }
10766     function getDeclarationIdentifier(node) {
10767         var name = getNameOfDeclaration(node);
10768         return name && isIdentifier(name) ? name : undefined;
10769     }
10770     /** @internal */
10771     function nodeHasName(statement, name) {
10772         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10773             return true;
10774         }
10775         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10776             return true;
10777         }
10778         return false;
10779     }
10780     ts.nodeHasName = nodeHasName;
10781     function getNameOfJSDocTypedef(declaration) {
10782         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10783     }
10784     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10785     /** @internal */
10786     function isNamedDeclaration(node) {
10787         return !!node.name; // A 'name' property should always be a DeclarationName.
10788     }
10789     ts.isNamedDeclaration = isNamedDeclaration;
10790     /** @internal */
10791     function getNonAssignedNameOfDeclaration(declaration) {
10792         switch (declaration.kind) {
10793             case 75 /* Identifier */:
10794                 return declaration;
10795             case 323 /* JSDocPropertyTag */:
10796             case 317 /* JSDocParameterTag */: {
10797                 var name = declaration.name;
10798                 if (name.kind === 153 /* QualifiedName */) {
10799                     return name.right;
10800                 }
10801                 break;
10802             }
10803             case 196 /* CallExpression */:
10804             case 209 /* BinaryExpression */: {
10805                 var expr_1 = declaration;
10806                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10807                     case 1 /* ExportsProperty */:
10808                     case 4 /* ThisProperty */:
10809                     case 5 /* Property */:
10810                     case 3 /* PrototypeProperty */:
10811                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10812                     case 7 /* ObjectDefinePropertyValue */:
10813                     case 8 /* ObjectDefinePropertyExports */:
10814                     case 9 /* ObjectDefinePrototypeProperty */:
10815                         return expr_1.arguments[1];
10816                     default:
10817                         return undefined;
10818                 }
10819             }
10820             case 322 /* JSDocTypedefTag */:
10821                 return getNameOfJSDocTypedef(declaration);
10822             case 316 /* JSDocEnumTag */:
10823                 return nameForNamelessJSDocTypedef(declaration);
10824             case 259 /* ExportAssignment */: {
10825                 var expression = declaration.expression;
10826                 return isIdentifier(expression) ? expression : undefined;
10827             }
10828             case 195 /* ElementAccessExpression */:
10829                 var expr = declaration;
10830                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10831                     return expr.argumentExpression;
10832                 }
10833         }
10834         return declaration.name;
10835     }
10836     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10837     function getNameOfDeclaration(declaration) {
10838         if (declaration === undefined)
10839             return undefined;
10840         return getNonAssignedNameOfDeclaration(declaration) ||
10841             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
10842     }
10843     ts.getNameOfDeclaration = getNameOfDeclaration;
10844     function getAssignedName(node) {
10845         if (!node.parent) {
10846             return undefined;
10847         }
10848         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
10849             return node.parent.name;
10850         }
10851         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
10852             if (isIdentifier(node.parent.left)) {
10853                 return node.parent.left;
10854             }
10855             else if (ts.isAccessExpression(node.parent.left)) {
10856                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
10857             }
10858         }
10859         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
10860             return node.parent.name;
10861         }
10862     }
10863     /**
10864      * Gets the JSDoc parameter tags for the node if present.
10865      *
10866      * @remarks Returns any JSDoc param tag whose name matches the provided
10867      * parameter, whether a param tag on a containing function
10868      * expression, or a param tag on a variable declaration whose
10869      * initializer is the containing function. The tags closest to the
10870      * node are returned first, so in the previous example, the param
10871      * tag on the containing function expression would be first.
10872      *
10873      * For binding patterns, parameter tags are matched by position.
10874      */
10875     function getJSDocParameterTags(param) {
10876         if (param.name) {
10877             if (isIdentifier(param.name)) {
10878                 var name_1 = param.name.escapedText;
10879                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
10880             }
10881             else {
10882                 var i = param.parent.parameters.indexOf(param);
10883                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
10884                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
10885                 if (i < paramTags.length) {
10886                     return [paramTags[i]];
10887                 }
10888             }
10889         }
10890         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
10891         return ts.emptyArray;
10892     }
10893     ts.getJSDocParameterTags = getJSDocParameterTags;
10894     /**
10895      * Gets the JSDoc type parameter tags for the node if present.
10896      *
10897      * @remarks Returns any JSDoc template tag whose names match the provided
10898      * parameter, whether a template tag on a containing function
10899      * expression, or a template tag on a variable declaration whose
10900      * initializer is the containing function. The tags closest to the
10901      * node are returned first, so in the previous example, the template
10902      * tag on the containing function expression would be first.
10903      */
10904     function getJSDocTypeParameterTags(param) {
10905         var name = param.name.escapedText;
10906         return getJSDocTags(param.parent).filter(function (tag) {
10907             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
10908         });
10909     }
10910     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
10911     /**
10912      * Return true if the node has JSDoc parameter tags.
10913      *
10914      * @remarks Includes parameter tags that are not directly on the node,
10915      * for example on a variable declaration whose initializer is a function expression.
10916      */
10917     function hasJSDocParameterTags(node) {
10918         return !!getFirstJSDocTag(node, isJSDocParameterTag);
10919     }
10920     ts.hasJSDocParameterTags = hasJSDocParameterTags;
10921     /** Gets the JSDoc augments tag for the node if present */
10922     function getJSDocAugmentsTag(node) {
10923         return getFirstJSDocTag(node, isJSDocAugmentsTag);
10924     }
10925     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
10926     /** Gets the JSDoc implements tags for the node if present */
10927     function getJSDocImplementsTags(node) {
10928         return getAllJSDocTags(node, isJSDocImplementsTag);
10929     }
10930     ts.getJSDocImplementsTags = getJSDocImplementsTags;
10931     /** Gets the JSDoc class tag for the node if present */
10932     function getJSDocClassTag(node) {
10933         return getFirstJSDocTag(node, isJSDocClassTag);
10934     }
10935     ts.getJSDocClassTag = getJSDocClassTag;
10936     /** Gets the JSDoc public tag for the node if present */
10937     function getJSDocPublicTag(node) {
10938         return getFirstJSDocTag(node, isJSDocPublicTag);
10939     }
10940     ts.getJSDocPublicTag = getJSDocPublicTag;
10941     /** Gets the JSDoc private tag for the node if present */
10942     function getJSDocPrivateTag(node) {
10943         return getFirstJSDocTag(node, isJSDocPrivateTag);
10944     }
10945     ts.getJSDocPrivateTag = getJSDocPrivateTag;
10946     /** Gets the JSDoc protected tag for the node if present */
10947     function getJSDocProtectedTag(node) {
10948         return getFirstJSDocTag(node, isJSDocProtectedTag);
10949     }
10950     ts.getJSDocProtectedTag = getJSDocProtectedTag;
10951     /** Gets the JSDoc protected tag for the node if present */
10952     function getJSDocReadonlyTag(node) {
10953         return getFirstJSDocTag(node, isJSDocReadonlyTag);
10954     }
10955     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
10956     /** Gets the JSDoc enum tag for the node if present */
10957     function getJSDocEnumTag(node) {
10958         return getFirstJSDocTag(node, isJSDocEnumTag);
10959     }
10960     ts.getJSDocEnumTag = getJSDocEnumTag;
10961     /** Gets the JSDoc this tag for the node if present */
10962     function getJSDocThisTag(node) {
10963         return getFirstJSDocTag(node, isJSDocThisTag);
10964     }
10965     ts.getJSDocThisTag = getJSDocThisTag;
10966     /** Gets the JSDoc return tag for the node if present */
10967     function getJSDocReturnTag(node) {
10968         return getFirstJSDocTag(node, isJSDocReturnTag);
10969     }
10970     ts.getJSDocReturnTag = getJSDocReturnTag;
10971     /** Gets the JSDoc template tag for the node if present */
10972     function getJSDocTemplateTag(node) {
10973         return getFirstJSDocTag(node, isJSDocTemplateTag);
10974     }
10975     ts.getJSDocTemplateTag = getJSDocTemplateTag;
10976     /** Gets the JSDoc type tag for the node if present and valid */
10977     function getJSDocTypeTag(node) {
10978         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
10979         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
10980         if (tag && tag.typeExpression && tag.typeExpression.type) {
10981             return tag;
10982         }
10983         return undefined;
10984     }
10985     ts.getJSDocTypeTag = getJSDocTypeTag;
10986     /**
10987      * Gets the type node for the node if provided via JSDoc.
10988      *
10989      * @remarks The search includes any JSDoc param tag that relates
10990      * to the provided parameter, for example a type tag on the
10991      * parameter itself, or a param tag on a containing function
10992      * expression, or a param tag on a variable declaration whose
10993      * initializer is the containing function. The tags closest to the
10994      * node are examined first, so in the previous example, the type
10995      * tag directly on the node would be returned.
10996      */
10997     function getJSDocType(node) {
10998         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
10999         if (!tag && isParameter(node)) {
11000             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11001         }
11002         return tag && tag.typeExpression && tag.typeExpression.type;
11003     }
11004     ts.getJSDocType = getJSDocType;
11005     /**
11006      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11007      *
11008      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11009      * gets the type from inside the braces, after the fat arrow, etc.
11010      */
11011     function getJSDocReturnType(node) {
11012         var returnTag = getJSDocReturnTag(node);
11013         if (returnTag && returnTag.typeExpression) {
11014             return returnTag.typeExpression.type;
11015         }
11016         var typeTag = getJSDocTypeTag(node);
11017         if (typeTag && typeTag.typeExpression) {
11018             var type = typeTag.typeExpression.type;
11019             if (isTypeLiteralNode(type)) {
11020                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11021                 return sig && sig.type;
11022             }
11023             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11024                 return type.type;
11025             }
11026         }
11027     }
11028     ts.getJSDocReturnType = getJSDocReturnType;
11029     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11030     function getJSDocTags(node) {
11031         var tags = node.jsDocCache;
11032         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11033         if (tags === undefined) {
11034             var comments = ts.getJSDocCommentsAndTags(node);
11035             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11036             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11037         }
11038         return tags;
11039     }
11040     ts.getJSDocTags = getJSDocTags;
11041     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11042     function getFirstJSDocTag(node, predicate) {
11043         return ts.find(getJSDocTags(node), predicate);
11044     }
11045     /** Gets all JSDoc tags that match a specified predicate */
11046     function getAllJSDocTags(node, predicate) {
11047         return getJSDocTags(node).filter(predicate);
11048     }
11049     ts.getAllJSDocTags = getAllJSDocTags;
11050     /** Gets all JSDoc tags of a specified kind */
11051     function getAllJSDocTagsOfKind(node, kind) {
11052         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11053     }
11054     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11055     /**
11056      * Gets the effective type parameters. If the node was parsed in a
11057      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11058      */
11059     function getEffectiveTypeParameterDeclarations(node) {
11060         if (isJSDocSignature(node)) {
11061             return ts.emptyArray;
11062         }
11063         if (ts.isJSDocTypeAlias(node)) {
11064             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11065             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11066         }
11067         if (node.typeParameters) {
11068             return node.typeParameters;
11069         }
11070         if (ts.isInJSFile(node)) {
11071             var decls = ts.getJSDocTypeParameterDeclarations(node);
11072             if (decls.length) {
11073                 return decls;
11074             }
11075             var typeTag = getJSDocType(node);
11076             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11077                 return typeTag.typeParameters;
11078             }
11079         }
11080         return ts.emptyArray;
11081     }
11082     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11083     function getEffectiveConstraintOfTypeParameter(node) {
11084         return node.constraint ? node.constraint :
11085             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11086                 undefined;
11087     }
11088     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11089     // #region
11090     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11091     // Literals
11092     function isNumericLiteral(node) {
11093         return node.kind === 8 /* NumericLiteral */;
11094     }
11095     ts.isNumericLiteral = isNumericLiteral;
11096     function isBigIntLiteral(node) {
11097         return node.kind === 9 /* BigIntLiteral */;
11098     }
11099     ts.isBigIntLiteral = isBigIntLiteral;
11100     function isStringLiteral(node) {
11101         return node.kind === 10 /* StringLiteral */;
11102     }
11103     ts.isStringLiteral = isStringLiteral;
11104     function isJsxText(node) {
11105         return node.kind === 11 /* JsxText */;
11106     }
11107     ts.isJsxText = isJsxText;
11108     function isRegularExpressionLiteral(node) {
11109         return node.kind === 13 /* RegularExpressionLiteral */;
11110     }
11111     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11112     function isNoSubstitutionTemplateLiteral(node) {
11113         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11114     }
11115     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11116     // Pseudo-literals
11117     function isTemplateHead(node) {
11118         return node.kind === 15 /* TemplateHead */;
11119     }
11120     ts.isTemplateHead = isTemplateHead;
11121     function isTemplateMiddle(node) {
11122         return node.kind === 16 /* TemplateMiddle */;
11123     }
11124     ts.isTemplateMiddle = isTemplateMiddle;
11125     function isTemplateTail(node) {
11126         return node.kind === 17 /* TemplateTail */;
11127     }
11128     ts.isTemplateTail = isTemplateTail;
11129     function isIdentifier(node) {
11130         return node.kind === 75 /* Identifier */;
11131     }
11132     ts.isIdentifier = isIdentifier;
11133     // Names
11134     function isQualifiedName(node) {
11135         return node.kind === 153 /* QualifiedName */;
11136     }
11137     ts.isQualifiedName = isQualifiedName;
11138     function isComputedPropertyName(node) {
11139         return node.kind === 154 /* ComputedPropertyName */;
11140     }
11141     ts.isComputedPropertyName = isComputedPropertyName;
11142     function isPrivateIdentifier(node) {
11143         return node.kind === 76 /* PrivateIdentifier */;
11144     }
11145     ts.isPrivateIdentifier = isPrivateIdentifier;
11146     function isIdentifierOrPrivateIdentifier(node) {
11147         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11148     }
11149     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11150     // Signature elements
11151     function isTypeParameterDeclaration(node) {
11152         return node.kind === 155 /* TypeParameter */;
11153     }
11154     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11155     function isParameter(node) {
11156         return node.kind === 156 /* Parameter */;
11157     }
11158     ts.isParameter = isParameter;
11159     function isDecorator(node) {
11160         return node.kind === 157 /* Decorator */;
11161     }
11162     ts.isDecorator = isDecorator;
11163     // TypeMember
11164     function isPropertySignature(node) {
11165         return node.kind === 158 /* PropertySignature */;
11166     }
11167     ts.isPropertySignature = isPropertySignature;
11168     function isPropertyDeclaration(node) {
11169         return node.kind === 159 /* PropertyDeclaration */;
11170     }
11171     ts.isPropertyDeclaration = isPropertyDeclaration;
11172     function isMethodSignature(node) {
11173         return node.kind === 160 /* MethodSignature */;
11174     }
11175     ts.isMethodSignature = isMethodSignature;
11176     function isMethodDeclaration(node) {
11177         return node.kind === 161 /* MethodDeclaration */;
11178     }
11179     ts.isMethodDeclaration = isMethodDeclaration;
11180     function isConstructorDeclaration(node) {
11181         return node.kind === 162 /* Constructor */;
11182     }
11183     ts.isConstructorDeclaration = isConstructorDeclaration;
11184     function isGetAccessorDeclaration(node) {
11185         return node.kind === 163 /* GetAccessor */;
11186     }
11187     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11188     function isSetAccessorDeclaration(node) {
11189         return node.kind === 164 /* SetAccessor */;
11190     }
11191     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11192     function isCallSignatureDeclaration(node) {
11193         return node.kind === 165 /* CallSignature */;
11194     }
11195     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11196     function isConstructSignatureDeclaration(node) {
11197         return node.kind === 166 /* ConstructSignature */;
11198     }
11199     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11200     function isIndexSignatureDeclaration(node) {
11201         return node.kind === 167 /* IndexSignature */;
11202     }
11203     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11204     /* @internal */
11205     function isGetOrSetAccessorDeclaration(node) {
11206         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11207     }
11208     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11209     // Type
11210     function isTypePredicateNode(node) {
11211         return node.kind === 168 /* TypePredicate */;
11212     }
11213     ts.isTypePredicateNode = isTypePredicateNode;
11214     function isTypeReferenceNode(node) {
11215         return node.kind === 169 /* TypeReference */;
11216     }
11217     ts.isTypeReferenceNode = isTypeReferenceNode;
11218     function isFunctionTypeNode(node) {
11219         return node.kind === 170 /* FunctionType */;
11220     }
11221     ts.isFunctionTypeNode = isFunctionTypeNode;
11222     function isConstructorTypeNode(node) {
11223         return node.kind === 171 /* ConstructorType */;
11224     }
11225     ts.isConstructorTypeNode = isConstructorTypeNode;
11226     function isTypeQueryNode(node) {
11227         return node.kind === 172 /* TypeQuery */;
11228     }
11229     ts.isTypeQueryNode = isTypeQueryNode;
11230     function isTypeLiteralNode(node) {
11231         return node.kind === 173 /* TypeLiteral */;
11232     }
11233     ts.isTypeLiteralNode = isTypeLiteralNode;
11234     function isArrayTypeNode(node) {
11235         return node.kind === 174 /* ArrayType */;
11236     }
11237     ts.isArrayTypeNode = isArrayTypeNode;
11238     function isTupleTypeNode(node) {
11239         return node.kind === 175 /* TupleType */;
11240     }
11241     ts.isTupleTypeNode = isTupleTypeNode;
11242     function isUnionTypeNode(node) {
11243         return node.kind === 178 /* UnionType */;
11244     }
11245     ts.isUnionTypeNode = isUnionTypeNode;
11246     function isIntersectionTypeNode(node) {
11247         return node.kind === 179 /* IntersectionType */;
11248     }
11249     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11250     function isConditionalTypeNode(node) {
11251         return node.kind === 180 /* ConditionalType */;
11252     }
11253     ts.isConditionalTypeNode = isConditionalTypeNode;
11254     function isInferTypeNode(node) {
11255         return node.kind === 181 /* InferType */;
11256     }
11257     ts.isInferTypeNode = isInferTypeNode;
11258     function isParenthesizedTypeNode(node) {
11259         return node.kind === 182 /* ParenthesizedType */;
11260     }
11261     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11262     function isThisTypeNode(node) {
11263         return node.kind === 183 /* ThisType */;
11264     }
11265     ts.isThisTypeNode = isThisTypeNode;
11266     function isTypeOperatorNode(node) {
11267         return node.kind === 184 /* TypeOperator */;
11268     }
11269     ts.isTypeOperatorNode = isTypeOperatorNode;
11270     function isIndexedAccessTypeNode(node) {
11271         return node.kind === 185 /* IndexedAccessType */;
11272     }
11273     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11274     function isMappedTypeNode(node) {
11275         return node.kind === 186 /* MappedType */;
11276     }
11277     ts.isMappedTypeNode = isMappedTypeNode;
11278     function isLiteralTypeNode(node) {
11279         return node.kind === 187 /* LiteralType */;
11280     }
11281     ts.isLiteralTypeNode = isLiteralTypeNode;
11282     function isImportTypeNode(node) {
11283         return node.kind === 188 /* ImportType */;
11284     }
11285     ts.isImportTypeNode = isImportTypeNode;
11286     // Binding patterns
11287     function isObjectBindingPattern(node) {
11288         return node.kind === 189 /* ObjectBindingPattern */;
11289     }
11290     ts.isObjectBindingPattern = isObjectBindingPattern;
11291     function isArrayBindingPattern(node) {
11292         return node.kind === 190 /* ArrayBindingPattern */;
11293     }
11294     ts.isArrayBindingPattern = isArrayBindingPattern;
11295     function isBindingElement(node) {
11296         return node.kind === 191 /* BindingElement */;
11297     }
11298     ts.isBindingElement = isBindingElement;
11299     // Expression
11300     function isArrayLiteralExpression(node) {
11301         return node.kind === 192 /* ArrayLiteralExpression */;
11302     }
11303     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11304     function isObjectLiteralExpression(node) {
11305         return node.kind === 193 /* ObjectLiteralExpression */;
11306     }
11307     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11308     function isPropertyAccessExpression(node) {
11309         return node.kind === 194 /* PropertyAccessExpression */;
11310     }
11311     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11312     function isPropertyAccessChain(node) {
11313         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11314     }
11315     ts.isPropertyAccessChain = isPropertyAccessChain;
11316     function isElementAccessExpression(node) {
11317         return node.kind === 195 /* ElementAccessExpression */;
11318     }
11319     ts.isElementAccessExpression = isElementAccessExpression;
11320     function isElementAccessChain(node) {
11321         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11322     }
11323     ts.isElementAccessChain = isElementAccessChain;
11324     function isCallExpression(node) {
11325         return node.kind === 196 /* CallExpression */;
11326     }
11327     ts.isCallExpression = isCallExpression;
11328     function isCallChain(node) {
11329         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11330     }
11331     ts.isCallChain = isCallChain;
11332     function isOptionalChain(node) {
11333         var kind = node.kind;
11334         return !!(node.flags & 32 /* OptionalChain */) &&
11335             (kind === 194 /* PropertyAccessExpression */
11336                 || kind === 195 /* ElementAccessExpression */
11337                 || kind === 196 /* CallExpression */
11338                 || kind === 218 /* NonNullExpression */);
11339     }
11340     ts.isOptionalChain = isOptionalChain;
11341     /* @internal */
11342     function isOptionalChainRoot(node) {
11343         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11344     }
11345     ts.isOptionalChainRoot = isOptionalChainRoot;
11346     /**
11347      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11348      */
11349     /* @internal */
11350     function isExpressionOfOptionalChainRoot(node) {
11351         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11352     }
11353     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11354     /**
11355      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11356      *
11357      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11358      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11359      * 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)
11360      * 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
11361      *   the end of the chain starting at `c?.`)
11362      * 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
11363      *   the end of the chain starting at `a?.`)
11364      */
11365     /* @internal */
11366     function isOutermostOptionalChain(node) {
11367         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11368             || isOptionalChainRoot(node.parent) // case 4
11369             || node !== node.parent.expression; // case 5
11370     }
11371     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11372     function isNullishCoalesce(node) {
11373         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11374     }
11375     ts.isNullishCoalesce = isNullishCoalesce;
11376     function isNewExpression(node) {
11377         return node.kind === 197 /* NewExpression */;
11378     }
11379     ts.isNewExpression = isNewExpression;
11380     function isTaggedTemplateExpression(node) {
11381         return node.kind === 198 /* TaggedTemplateExpression */;
11382     }
11383     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11384     function isTypeAssertion(node) {
11385         return node.kind === 199 /* TypeAssertionExpression */;
11386     }
11387     ts.isTypeAssertion = isTypeAssertion;
11388     function isConstTypeReference(node) {
11389         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11390             node.typeName.escapedText === "const" && !node.typeArguments;
11391     }
11392     ts.isConstTypeReference = isConstTypeReference;
11393     function isParenthesizedExpression(node) {
11394         return node.kind === 200 /* ParenthesizedExpression */;
11395     }
11396     ts.isParenthesizedExpression = isParenthesizedExpression;
11397     function skipPartiallyEmittedExpressions(node) {
11398         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11399     }
11400     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11401     function isFunctionExpression(node) {
11402         return node.kind === 201 /* FunctionExpression */;
11403     }
11404     ts.isFunctionExpression = isFunctionExpression;
11405     function isArrowFunction(node) {
11406         return node.kind === 202 /* ArrowFunction */;
11407     }
11408     ts.isArrowFunction = isArrowFunction;
11409     function isDeleteExpression(node) {
11410         return node.kind === 203 /* DeleteExpression */;
11411     }
11412     ts.isDeleteExpression = isDeleteExpression;
11413     function isTypeOfExpression(node) {
11414         return node.kind === 204 /* TypeOfExpression */;
11415     }
11416     ts.isTypeOfExpression = isTypeOfExpression;
11417     function isVoidExpression(node) {
11418         return node.kind === 205 /* VoidExpression */;
11419     }
11420     ts.isVoidExpression = isVoidExpression;
11421     function isAwaitExpression(node) {
11422         return node.kind === 206 /* AwaitExpression */;
11423     }
11424     ts.isAwaitExpression = isAwaitExpression;
11425     function isPrefixUnaryExpression(node) {
11426         return node.kind === 207 /* PrefixUnaryExpression */;
11427     }
11428     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11429     function isPostfixUnaryExpression(node) {
11430         return node.kind === 208 /* PostfixUnaryExpression */;
11431     }
11432     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11433     function isBinaryExpression(node) {
11434         return node.kind === 209 /* BinaryExpression */;
11435     }
11436     ts.isBinaryExpression = isBinaryExpression;
11437     function isConditionalExpression(node) {
11438         return node.kind === 210 /* ConditionalExpression */;
11439     }
11440     ts.isConditionalExpression = isConditionalExpression;
11441     function isTemplateExpression(node) {
11442         return node.kind === 211 /* TemplateExpression */;
11443     }
11444     ts.isTemplateExpression = isTemplateExpression;
11445     function isYieldExpression(node) {
11446         return node.kind === 212 /* YieldExpression */;
11447     }
11448     ts.isYieldExpression = isYieldExpression;
11449     function isSpreadElement(node) {
11450         return node.kind === 213 /* SpreadElement */;
11451     }
11452     ts.isSpreadElement = isSpreadElement;
11453     function isClassExpression(node) {
11454         return node.kind === 214 /* ClassExpression */;
11455     }
11456     ts.isClassExpression = isClassExpression;
11457     function isOmittedExpression(node) {
11458         return node.kind === 215 /* OmittedExpression */;
11459     }
11460     ts.isOmittedExpression = isOmittedExpression;
11461     function isExpressionWithTypeArguments(node) {
11462         return node.kind === 216 /* ExpressionWithTypeArguments */;
11463     }
11464     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11465     function isAsExpression(node) {
11466         return node.kind === 217 /* AsExpression */;
11467     }
11468     ts.isAsExpression = isAsExpression;
11469     function isNonNullExpression(node) {
11470         return node.kind === 218 /* NonNullExpression */;
11471     }
11472     ts.isNonNullExpression = isNonNullExpression;
11473     function isNonNullChain(node) {
11474         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11475     }
11476     ts.isNonNullChain = isNonNullChain;
11477     function isMetaProperty(node) {
11478         return node.kind === 219 /* MetaProperty */;
11479     }
11480     ts.isMetaProperty = isMetaProperty;
11481     // Misc
11482     function isTemplateSpan(node) {
11483         return node.kind === 221 /* TemplateSpan */;
11484     }
11485     ts.isTemplateSpan = isTemplateSpan;
11486     function isSemicolonClassElement(node) {
11487         return node.kind === 222 /* SemicolonClassElement */;
11488     }
11489     ts.isSemicolonClassElement = isSemicolonClassElement;
11490     // Block
11491     function isBlock(node) {
11492         return node.kind === 223 /* Block */;
11493     }
11494     ts.isBlock = isBlock;
11495     function isVariableStatement(node) {
11496         return node.kind === 225 /* VariableStatement */;
11497     }
11498     ts.isVariableStatement = isVariableStatement;
11499     function isEmptyStatement(node) {
11500         return node.kind === 224 /* EmptyStatement */;
11501     }
11502     ts.isEmptyStatement = isEmptyStatement;
11503     function isExpressionStatement(node) {
11504         return node.kind === 226 /* ExpressionStatement */;
11505     }
11506     ts.isExpressionStatement = isExpressionStatement;
11507     function isIfStatement(node) {
11508         return node.kind === 227 /* IfStatement */;
11509     }
11510     ts.isIfStatement = isIfStatement;
11511     function isDoStatement(node) {
11512         return node.kind === 228 /* DoStatement */;
11513     }
11514     ts.isDoStatement = isDoStatement;
11515     function isWhileStatement(node) {
11516         return node.kind === 229 /* WhileStatement */;
11517     }
11518     ts.isWhileStatement = isWhileStatement;
11519     function isForStatement(node) {
11520         return node.kind === 230 /* ForStatement */;
11521     }
11522     ts.isForStatement = isForStatement;
11523     function isForInStatement(node) {
11524         return node.kind === 231 /* ForInStatement */;
11525     }
11526     ts.isForInStatement = isForInStatement;
11527     function isForOfStatement(node) {
11528         return node.kind === 232 /* ForOfStatement */;
11529     }
11530     ts.isForOfStatement = isForOfStatement;
11531     function isContinueStatement(node) {
11532         return node.kind === 233 /* ContinueStatement */;
11533     }
11534     ts.isContinueStatement = isContinueStatement;
11535     function isBreakStatement(node) {
11536         return node.kind === 234 /* BreakStatement */;
11537     }
11538     ts.isBreakStatement = isBreakStatement;
11539     function isBreakOrContinueStatement(node) {
11540         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11541     }
11542     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11543     function isReturnStatement(node) {
11544         return node.kind === 235 /* ReturnStatement */;
11545     }
11546     ts.isReturnStatement = isReturnStatement;
11547     function isWithStatement(node) {
11548         return node.kind === 236 /* WithStatement */;
11549     }
11550     ts.isWithStatement = isWithStatement;
11551     function isSwitchStatement(node) {
11552         return node.kind === 237 /* SwitchStatement */;
11553     }
11554     ts.isSwitchStatement = isSwitchStatement;
11555     function isLabeledStatement(node) {
11556         return node.kind === 238 /* LabeledStatement */;
11557     }
11558     ts.isLabeledStatement = isLabeledStatement;
11559     function isThrowStatement(node) {
11560         return node.kind === 239 /* ThrowStatement */;
11561     }
11562     ts.isThrowStatement = isThrowStatement;
11563     function isTryStatement(node) {
11564         return node.kind === 240 /* TryStatement */;
11565     }
11566     ts.isTryStatement = isTryStatement;
11567     function isDebuggerStatement(node) {
11568         return node.kind === 241 /* DebuggerStatement */;
11569     }
11570     ts.isDebuggerStatement = isDebuggerStatement;
11571     function isVariableDeclaration(node) {
11572         return node.kind === 242 /* VariableDeclaration */;
11573     }
11574     ts.isVariableDeclaration = isVariableDeclaration;
11575     function isVariableDeclarationList(node) {
11576         return node.kind === 243 /* VariableDeclarationList */;
11577     }
11578     ts.isVariableDeclarationList = isVariableDeclarationList;
11579     function isFunctionDeclaration(node) {
11580         return node.kind === 244 /* FunctionDeclaration */;
11581     }
11582     ts.isFunctionDeclaration = isFunctionDeclaration;
11583     function isClassDeclaration(node) {
11584         return node.kind === 245 /* ClassDeclaration */;
11585     }
11586     ts.isClassDeclaration = isClassDeclaration;
11587     function isInterfaceDeclaration(node) {
11588         return node.kind === 246 /* InterfaceDeclaration */;
11589     }
11590     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11591     function isTypeAliasDeclaration(node) {
11592         return node.kind === 247 /* TypeAliasDeclaration */;
11593     }
11594     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11595     function isEnumDeclaration(node) {
11596         return node.kind === 248 /* EnumDeclaration */;
11597     }
11598     ts.isEnumDeclaration = isEnumDeclaration;
11599     function isModuleDeclaration(node) {
11600         return node.kind === 249 /* ModuleDeclaration */;
11601     }
11602     ts.isModuleDeclaration = isModuleDeclaration;
11603     function isModuleBlock(node) {
11604         return node.kind === 250 /* ModuleBlock */;
11605     }
11606     ts.isModuleBlock = isModuleBlock;
11607     function isCaseBlock(node) {
11608         return node.kind === 251 /* CaseBlock */;
11609     }
11610     ts.isCaseBlock = isCaseBlock;
11611     function isNamespaceExportDeclaration(node) {
11612         return node.kind === 252 /* NamespaceExportDeclaration */;
11613     }
11614     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11615     function isImportEqualsDeclaration(node) {
11616         return node.kind === 253 /* ImportEqualsDeclaration */;
11617     }
11618     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11619     function isImportDeclaration(node) {
11620         return node.kind === 254 /* ImportDeclaration */;
11621     }
11622     ts.isImportDeclaration = isImportDeclaration;
11623     function isImportClause(node) {
11624         return node.kind === 255 /* ImportClause */;
11625     }
11626     ts.isImportClause = isImportClause;
11627     function isNamespaceImport(node) {
11628         return node.kind === 256 /* NamespaceImport */;
11629     }
11630     ts.isNamespaceImport = isNamespaceImport;
11631     function isNamespaceExport(node) {
11632         return node.kind === 262 /* NamespaceExport */;
11633     }
11634     ts.isNamespaceExport = isNamespaceExport;
11635     function isNamedExportBindings(node) {
11636         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11637     }
11638     ts.isNamedExportBindings = isNamedExportBindings;
11639     function isNamedImports(node) {
11640         return node.kind === 257 /* NamedImports */;
11641     }
11642     ts.isNamedImports = isNamedImports;
11643     function isImportSpecifier(node) {
11644         return node.kind === 258 /* ImportSpecifier */;
11645     }
11646     ts.isImportSpecifier = isImportSpecifier;
11647     function isExportAssignment(node) {
11648         return node.kind === 259 /* ExportAssignment */;
11649     }
11650     ts.isExportAssignment = isExportAssignment;
11651     function isExportDeclaration(node) {
11652         return node.kind === 260 /* ExportDeclaration */;
11653     }
11654     ts.isExportDeclaration = isExportDeclaration;
11655     function isNamedExports(node) {
11656         return node.kind === 261 /* NamedExports */;
11657     }
11658     ts.isNamedExports = isNamedExports;
11659     function isExportSpecifier(node) {
11660         return node.kind === 263 /* ExportSpecifier */;
11661     }
11662     ts.isExportSpecifier = isExportSpecifier;
11663     function isMissingDeclaration(node) {
11664         return node.kind === 264 /* MissingDeclaration */;
11665     }
11666     ts.isMissingDeclaration = isMissingDeclaration;
11667     // Module References
11668     function isExternalModuleReference(node) {
11669         return node.kind === 265 /* ExternalModuleReference */;
11670     }
11671     ts.isExternalModuleReference = isExternalModuleReference;
11672     // JSX
11673     function isJsxElement(node) {
11674         return node.kind === 266 /* JsxElement */;
11675     }
11676     ts.isJsxElement = isJsxElement;
11677     function isJsxSelfClosingElement(node) {
11678         return node.kind === 267 /* JsxSelfClosingElement */;
11679     }
11680     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11681     function isJsxOpeningElement(node) {
11682         return node.kind === 268 /* JsxOpeningElement */;
11683     }
11684     ts.isJsxOpeningElement = isJsxOpeningElement;
11685     function isJsxClosingElement(node) {
11686         return node.kind === 269 /* JsxClosingElement */;
11687     }
11688     ts.isJsxClosingElement = isJsxClosingElement;
11689     function isJsxFragment(node) {
11690         return node.kind === 270 /* JsxFragment */;
11691     }
11692     ts.isJsxFragment = isJsxFragment;
11693     function isJsxOpeningFragment(node) {
11694         return node.kind === 271 /* JsxOpeningFragment */;
11695     }
11696     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11697     function isJsxClosingFragment(node) {
11698         return node.kind === 272 /* JsxClosingFragment */;
11699     }
11700     ts.isJsxClosingFragment = isJsxClosingFragment;
11701     function isJsxAttribute(node) {
11702         return node.kind === 273 /* JsxAttribute */;
11703     }
11704     ts.isJsxAttribute = isJsxAttribute;
11705     function isJsxAttributes(node) {
11706         return node.kind === 274 /* JsxAttributes */;
11707     }
11708     ts.isJsxAttributes = isJsxAttributes;
11709     function isJsxSpreadAttribute(node) {
11710         return node.kind === 275 /* JsxSpreadAttribute */;
11711     }
11712     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11713     function isJsxExpression(node) {
11714         return node.kind === 276 /* JsxExpression */;
11715     }
11716     ts.isJsxExpression = isJsxExpression;
11717     // Clauses
11718     function isCaseClause(node) {
11719         return node.kind === 277 /* CaseClause */;
11720     }
11721     ts.isCaseClause = isCaseClause;
11722     function isDefaultClause(node) {
11723         return node.kind === 278 /* DefaultClause */;
11724     }
11725     ts.isDefaultClause = isDefaultClause;
11726     function isHeritageClause(node) {
11727         return node.kind === 279 /* HeritageClause */;
11728     }
11729     ts.isHeritageClause = isHeritageClause;
11730     function isCatchClause(node) {
11731         return node.kind === 280 /* CatchClause */;
11732     }
11733     ts.isCatchClause = isCatchClause;
11734     // Property assignments
11735     function isPropertyAssignment(node) {
11736         return node.kind === 281 /* PropertyAssignment */;
11737     }
11738     ts.isPropertyAssignment = isPropertyAssignment;
11739     function isShorthandPropertyAssignment(node) {
11740         return node.kind === 282 /* ShorthandPropertyAssignment */;
11741     }
11742     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11743     function isSpreadAssignment(node) {
11744         return node.kind === 283 /* SpreadAssignment */;
11745     }
11746     ts.isSpreadAssignment = isSpreadAssignment;
11747     // Enum
11748     function isEnumMember(node) {
11749         return node.kind === 284 /* EnumMember */;
11750     }
11751     ts.isEnumMember = isEnumMember;
11752     // Top-level nodes
11753     function isSourceFile(node) {
11754         return node.kind === 290 /* SourceFile */;
11755     }
11756     ts.isSourceFile = isSourceFile;
11757     function isBundle(node) {
11758         return node.kind === 291 /* Bundle */;
11759     }
11760     ts.isBundle = isBundle;
11761     function isUnparsedSource(node) {
11762         return node.kind === 292 /* UnparsedSource */;
11763     }
11764     ts.isUnparsedSource = isUnparsedSource;
11765     function isUnparsedPrepend(node) {
11766         return node.kind === 286 /* UnparsedPrepend */;
11767     }
11768     ts.isUnparsedPrepend = isUnparsedPrepend;
11769     function isUnparsedTextLike(node) {
11770         switch (node.kind) {
11771             case 287 /* UnparsedText */:
11772             case 288 /* UnparsedInternalText */:
11773                 return true;
11774             default:
11775                 return false;
11776         }
11777     }
11778     ts.isUnparsedTextLike = isUnparsedTextLike;
11779     function isUnparsedNode(node) {
11780         return isUnparsedTextLike(node) ||
11781             node.kind === 285 /* UnparsedPrologue */ ||
11782             node.kind === 289 /* UnparsedSyntheticReference */;
11783     }
11784     ts.isUnparsedNode = isUnparsedNode;
11785     // JSDoc
11786     function isJSDocTypeExpression(node) {
11787         return node.kind === 294 /* JSDocTypeExpression */;
11788     }
11789     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11790     function isJSDocAllType(node) {
11791         return node.kind === 295 /* JSDocAllType */;
11792     }
11793     ts.isJSDocAllType = isJSDocAllType;
11794     function isJSDocUnknownType(node) {
11795         return node.kind === 296 /* JSDocUnknownType */;
11796     }
11797     ts.isJSDocUnknownType = isJSDocUnknownType;
11798     function isJSDocNullableType(node) {
11799         return node.kind === 297 /* JSDocNullableType */;
11800     }
11801     ts.isJSDocNullableType = isJSDocNullableType;
11802     function isJSDocNonNullableType(node) {
11803         return node.kind === 298 /* JSDocNonNullableType */;
11804     }
11805     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11806     function isJSDocOptionalType(node) {
11807         return node.kind === 299 /* JSDocOptionalType */;
11808     }
11809     ts.isJSDocOptionalType = isJSDocOptionalType;
11810     function isJSDocFunctionType(node) {
11811         return node.kind === 300 /* JSDocFunctionType */;
11812     }
11813     ts.isJSDocFunctionType = isJSDocFunctionType;
11814     function isJSDocVariadicType(node) {
11815         return node.kind === 301 /* JSDocVariadicType */;
11816     }
11817     ts.isJSDocVariadicType = isJSDocVariadicType;
11818     function isJSDoc(node) {
11819         return node.kind === 303 /* JSDocComment */;
11820     }
11821     ts.isJSDoc = isJSDoc;
11822     function isJSDocAuthorTag(node) {
11823         return node.kind === 309 /* JSDocAuthorTag */;
11824     }
11825     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11826     function isJSDocAugmentsTag(node) {
11827         return node.kind === 307 /* JSDocAugmentsTag */;
11828     }
11829     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11830     function isJSDocImplementsTag(node) {
11831         return node.kind === 308 /* JSDocImplementsTag */;
11832     }
11833     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11834     function isJSDocClassTag(node) {
11835         return node.kind === 310 /* JSDocClassTag */;
11836     }
11837     ts.isJSDocClassTag = isJSDocClassTag;
11838     function isJSDocPublicTag(node) {
11839         return node.kind === 311 /* JSDocPublicTag */;
11840     }
11841     ts.isJSDocPublicTag = isJSDocPublicTag;
11842     function isJSDocPrivateTag(node) {
11843         return node.kind === 312 /* JSDocPrivateTag */;
11844     }
11845     ts.isJSDocPrivateTag = isJSDocPrivateTag;
11846     function isJSDocProtectedTag(node) {
11847         return node.kind === 313 /* JSDocProtectedTag */;
11848     }
11849     ts.isJSDocProtectedTag = isJSDocProtectedTag;
11850     function isJSDocReadonlyTag(node) {
11851         return node.kind === 314 /* JSDocReadonlyTag */;
11852     }
11853     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
11854     function isJSDocEnumTag(node) {
11855         return node.kind === 316 /* JSDocEnumTag */;
11856     }
11857     ts.isJSDocEnumTag = isJSDocEnumTag;
11858     function isJSDocThisTag(node) {
11859         return node.kind === 319 /* JSDocThisTag */;
11860     }
11861     ts.isJSDocThisTag = isJSDocThisTag;
11862     function isJSDocParameterTag(node) {
11863         return node.kind === 317 /* JSDocParameterTag */;
11864     }
11865     ts.isJSDocParameterTag = isJSDocParameterTag;
11866     function isJSDocReturnTag(node) {
11867         return node.kind === 318 /* JSDocReturnTag */;
11868     }
11869     ts.isJSDocReturnTag = isJSDocReturnTag;
11870     function isJSDocTypeTag(node) {
11871         return node.kind === 320 /* JSDocTypeTag */;
11872     }
11873     ts.isJSDocTypeTag = isJSDocTypeTag;
11874     function isJSDocTemplateTag(node) {
11875         return node.kind === 321 /* JSDocTemplateTag */;
11876     }
11877     ts.isJSDocTemplateTag = isJSDocTemplateTag;
11878     function isJSDocTypedefTag(node) {
11879         return node.kind === 322 /* JSDocTypedefTag */;
11880     }
11881     ts.isJSDocTypedefTag = isJSDocTypedefTag;
11882     function isJSDocPropertyTag(node) {
11883         return node.kind === 323 /* JSDocPropertyTag */;
11884     }
11885     ts.isJSDocPropertyTag = isJSDocPropertyTag;
11886     function isJSDocPropertyLikeTag(node) {
11887         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
11888     }
11889     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11890     function isJSDocTypeLiteral(node) {
11891         return node.kind === 304 /* JSDocTypeLiteral */;
11892     }
11893     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
11894     function isJSDocCallbackTag(node) {
11895         return node.kind === 315 /* JSDocCallbackTag */;
11896     }
11897     ts.isJSDocCallbackTag = isJSDocCallbackTag;
11898     function isJSDocSignature(node) {
11899         return node.kind === 305 /* JSDocSignature */;
11900     }
11901     ts.isJSDocSignature = isJSDocSignature;
11902     // #endregion
11903     // #region
11904     // Node tests
11905     //
11906     // All node tests in the following list should *not* reference parent pointers so that
11907     // they may be used with transformations.
11908     /* @internal */
11909     function isSyntaxList(n) {
11910         return n.kind === 324 /* SyntaxList */;
11911     }
11912     ts.isSyntaxList = isSyntaxList;
11913     /* @internal */
11914     function isNode(node) {
11915         return isNodeKind(node.kind);
11916     }
11917     ts.isNode = isNode;
11918     /* @internal */
11919     function isNodeKind(kind) {
11920         return kind >= 153 /* FirstNode */;
11921     }
11922     ts.isNodeKind = isNodeKind;
11923     /**
11924      * True if node is of some token syntax kind.
11925      * For example, this is true for an IfKeyword but not for an IfStatement.
11926      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11927      */
11928     function isToken(n) {
11929         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
11930     }
11931     ts.isToken = isToken;
11932     // Node Arrays
11933     /* @internal */
11934     function isNodeArray(array) {
11935         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11936     }
11937     ts.isNodeArray = isNodeArray;
11938     // Literals
11939     /* @internal */
11940     function isLiteralKind(kind) {
11941         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11942     }
11943     ts.isLiteralKind = isLiteralKind;
11944     function isLiteralExpression(node) {
11945         return isLiteralKind(node.kind);
11946     }
11947     ts.isLiteralExpression = isLiteralExpression;
11948     // Pseudo-literals
11949     /* @internal */
11950     function isTemplateLiteralKind(kind) {
11951         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11952     }
11953     ts.isTemplateLiteralKind = isTemplateLiteralKind;
11954     function isTemplateLiteralToken(node) {
11955         return isTemplateLiteralKind(node.kind);
11956     }
11957     ts.isTemplateLiteralToken = isTemplateLiteralToken;
11958     function isTemplateMiddleOrTemplateTail(node) {
11959         var kind = node.kind;
11960         return kind === 16 /* TemplateMiddle */
11961             || kind === 17 /* TemplateTail */;
11962     }
11963     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11964     function isImportOrExportSpecifier(node) {
11965         return isImportSpecifier(node) || isExportSpecifier(node);
11966     }
11967     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11968     function isTypeOnlyImportOrExportDeclaration(node) {
11969         switch (node.kind) {
11970             case 258 /* ImportSpecifier */:
11971             case 263 /* ExportSpecifier */:
11972                 return node.parent.parent.isTypeOnly;
11973             case 256 /* NamespaceImport */:
11974                 return node.parent.isTypeOnly;
11975             case 255 /* ImportClause */:
11976                 return node.isTypeOnly;
11977             default:
11978                 return false;
11979         }
11980     }
11981     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
11982     function isStringTextContainingNode(node) {
11983         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
11984     }
11985     ts.isStringTextContainingNode = isStringTextContainingNode;
11986     // Identifiers
11987     /* @internal */
11988     function isGeneratedIdentifier(node) {
11989         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
11990     }
11991     ts.isGeneratedIdentifier = isGeneratedIdentifier;
11992     // Private Identifiers
11993     /*@internal*/
11994     function isPrivateIdentifierPropertyDeclaration(node) {
11995         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
11996     }
11997     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
11998     /*@internal*/
11999     function isPrivateIdentifierPropertyAccessExpression(node) {
12000         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12001     }
12002     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12003     // Keywords
12004     /* @internal */
12005     function isModifierKind(token) {
12006         switch (token) {
12007             case 122 /* AbstractKeyword */:
12008             case 126 /* AsyncKeyword */:
12009             case 81 /* ConstKeyword */:
12010             case 130 /* DeclareKeyword */:
12011             case 84 /* DefaultKeyword */:
12012             case 89 /* ExportKeyword */:
12013             case 119 /* PublicKeyword */:
12014             case 117 /* PrivateKeyword */:
12015             case 118 /* ProtectedKeyword */:
12016             case 138 /* ReadonlyKeyword */:
12017             case 120 /* StaticKeyword */:
12018                 return true;
12019         }
12020         return false;
12021     }
12022     ts.isModifierKind = isModifierKind;
12023     /* @internal */
12024     function isParameterPropertyModifier(kind) {
12025         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12026     }
12027     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12028     /* @internal */
12029     function isClassMemberModifier(idToken) {
12030         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12031     }
12032     ts.isClassMemberModifier = isClassMemberModifier;
12033     function isModifier(node) {
12034         return isModifierKind(node.kind);
12035     }
12036     ts.isModifier = isModifier;
12037     function isEntityName(node) {
12038         var kind = node.kind;
12039         return kind === 153 /* QualifiedName */
12040             || kind === 75 /* Identifier */;
12041     }
12042     ts.isEntityName = isEntityName;
12043     function isPropertyName(node) {
12044         var kind = node.kind;
12045         return kind === 75 /* Identifier */
12046             || kind === 76 /* PrivateIdentifier */
12047             || kind === 10 /* StringLiteral */
12048             || kind === 8 /* NumericLiteral */
12049             || kind === 154 /* ComputedPropertyName */;
12050     }
12051     ts.isPropertyName = isPropertyName;
12052     function isBindingName(node) {
12053         var kind = node.kind;
12054         return kind === 75 /* Identifier */
12055             || kind === 189 /* ObjectBindingPattern */
12056             || kind === 190 /* ArrayBindingPattern */;
12057     }
12058     ts.isBindingName = isBindingName;
12059     // Functions
12060     function isFunctionLike(node) {
12061         return node && isFunctionLikeKind(node.kind);
12062     }
12063     ts.isFunctionLike = isFunctionLike;
12064     /* @internal */
12065     function isFunctionLikeDeclaration(node) {
12066         return node && isFunctionLikeDeclarationKind(node.kind);
12067     }
12068     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12069     function isFunctionLikeDeclarationKind(kind) {
12070         switch (kind) {
12071             case 244 /* FunctionDeclaration */:
12072             case 161 /* MethodDeclaration */:
12073             case 162 /* Constructor */:
12074             case 163 /* GetAccessor */:
12075             case 164 /* SetAccessor */:
12076             case 201 /* FunctionExpression */:
12077             case 202 /* ArrowFunction */:
12078                 return true;
12079             default:
12080                 return false;
12081         }
12082     }
12083     /* @internal */
12084     function isFunctionLikeKind(kind) {
12085         switch (kind) {
12086             case 160 /* MethodSignature */:
12087             case 165 /* CallSignature */:
12088             case 305 /* JSDocSignature */:
12089             case 166 /* ConstructSignature */:
12090             case 167 /* IndexSignature */:
12091             case 170 /* FunctionType */:
12092             case 300 /* JSDocFunctionType */:
12093             case 171 /* ConstructorType */:
12094                 return true;
12095             default:
12096                 return isFunctionLikeDeclarationKind(kind);
12097         }
12098     }
12099     ts.isFunctionLikeKind = isFunctionLikeKind;
12100     /* @internal */
12101     function isFunctionOrModuleBlock(node) {
12102         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12103     }
12104     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12105     // Classes
12106     function isClassElement(node) {
12107         var kind = node.kind;
12108         return kind === 162 /* Constructor */
12109             || kind === 159 /* PropertyDeclaration */
12110             || kind === 161 /* MethodDeclaration */
12111             || kind === 163 /* GetAccessor */
12112             || kind === 164 /* SetAccessor */
12113             || kind === 167 /* IndexSignature */
12114             || kind === 222 /* SemicolonClassElement */;
12115     }
12116     ts.isClassElement = isClassElement;
12117     function isClassLike(node) {
12118         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12119     }
12120     ts.isClassLike = isClassLike;
12121     function isAccessor(node) {
12122         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12123     }
12124     ts.isAccessor = isAccessor;
12125     /* @internal */
12126     function isMethodOrAccessor(node) {
12127         switch (node.kind) {
12128             case 161 /* MethodDeclaration */:
12129             case 163 /* GetAccessor */:
12130             case 164 /* SetAccessor */:
12131                 return true;
12132             default:
12133                 return false;
12134         }
12135     }
12136     ts.isMethodOrAccessor = isMethodOrAccessor;
12137     // Type members
12138     function isTypeElement(node) {
12139         var kind = node.kind;
12140         return kind === 166 /* ConstructSignature */
12141             || kind === 165 /* CallSignature */
12142             || kind === 158 /* PropertySignature */
12143             || kind === 160 /* MethodSignature */
12144             || kind === 167 /* IndexSignature */;
12145     }
12146     ts.isTypeElement = isTypeElement;
12147     function isClassOrTypeElement(node) {
12148         return isTypeElement(node) || isClassElement(node);
12149     }
12150     ts.isClassOrTypeElement = isClassOrTypeElement;
12151     function isObjectLiteralElementLike(node) {
12152         var kind = node.kind;
12153         return kind === 281 /* PropertyAssignment */
12154             || kind === 282 /* ShorthandPropertyAssignment */
12155             || kind === 283 /* SpreadAssignment */
12156             || kind === 161 /* MethodDeclaration */
12157             || kind === 163 /* GetAccessor */
12158             || kind === 164 /* SetAccessor */;
12159     }
12160     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12161     // Type
12162     /**
12163      * Node test that determines whether a node is a valid type node.
12164      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12165      * of a TypeNode.
12166      */
12167     function isTypeNode(node) {
12168         return ts.isTypeNodeKind(node.kind);
12169     }
12170     ts.isTypeNode = isTypeNode;
12171     function isFunctionOrConstructorTypeNode(node) {
12172         switch (node.kind) {
12173             case 170 /* FunctionType */:
12174             case 171 /* ConstructorType */:
12175                 return true;
12176         }
12177         return false;
12178     }
12179     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12180     // Binding patterns
12181     /* @internal */
12182     function isBindingPattern(node) {
12183         if (node) {
12184             var kind = node.kind;
12185             return kind === 190 /* ArrayBindingPattern */
12186                 || kind === 189 /* ObjectBindingPattern */;
12187         }
12188         return false;
12189     }
12190     ts.isBindingPattern = isBindingPattern;
12191     /* @internal */
12192     function isAssignmentPattern(node) {
12193         var kind = node.kind;
12194         return kind === 192 /* ArrayLiteralExpression */
12195             || kind === 193 /* ObjectLiteralExpression */;
12196     }
12197     ts.isAssignmentPattern = isAssignmentPattern;
12198     /* @internal */
12199     function isArrayBindingElement(node) {
12200         var kind = node.kind;
12201         return kind === 191 /* BindingElement */
12202             || kind === 215 /* OmittedExpression */;
12203     }
12204     ts.isArrayBindingElement = isArrayBindingElement;
12205     /**
12206      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12207      */
12208     /* @internal */
12209     function isDeclarationBindingElement(bindingElement) {
12210         switch (bindingElement.kind) {
12211             case 242 /* VariableDeclaration */:
12212             case 156 /* Parameter */:
12213             case 191 /* BindingElement */:
12214                 return true;
12215         }
12216         return false;
12217     }
12218     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12219     /**
12220      * Determines whether a node is a BindingOrAssignmentPattern
12221      */
12222     /* @internal */
12223     function isBindingOrAssignmentPattern(node) {
12224         return isObjectBindingOrAssignmentPattern(node)
12225             || isArrayBindingOrAssignmentPattern(node);
12226     }
12227     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12228     /**
12229      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12230      */
12231     /* @internal */
12232     function isObjectBindingOrAssignmentPattern(node) {
12233         switch (node.kind) {
12234             case 189 /* ObjectBindingPattern */:
12235             case 193 /* ObjectLiteralExpression */:
12236                 return true;
12237         }
12238         return false;
12239     }
12240     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12241     /**
12242      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12243      */
12244     /* @internal */
12245     function isArrayBindingOrAssignmentPattern(node) {
12246         switch (node.kind) {
12247             case 190 /* ArrayBindingPattern */:
12248             case 192 /* ArrayLiteralExpression */:
12249                 return true;
12250         }
12251         return false;
12252     }
12253     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12254     /* @internal */
12255     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12256         var kind = node.kind;
12257         return kind === 194 /* PropertyAccessExpression */
12258             || kind === 153 /* QualifiedName */
12259             || kind === 188 /* ImportType */;
12260     }
12261     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12262     // Expression
12263     function isPropertyAccessOrQualifiedName(node) {
12264         var kind = node.kind;
12265         return kind === 194 /* PropertyAccessExpression */
12266             || kind === 153 /* QualifiedName */;
12267     }
12268     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12269     function isCallLikeExpression(node) {
12270         switch (node.kind) {
12271             case 268 /* JsxOpeningElement */:
12272             case 267 /* JsxSelfClosingElement */:
12273             case 196 /* CallExpression */:
12274             case 197 /* NewExpression */:
12275             case 198 /* TaggedTemplateExpression */:
12276             case 157 /* Decorator */:
12277                 return true;
12278             default:
12279                 return false;
12280         }
12281     }
12282     ts.isCallLikeExpression = isCallLikeExpression;
12283     function isCallOrNewExpression(node) {
12284         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12285     }
12286     ts.isCallOrNewExpression = isCallOrNewExpression;
12287     function isTemplateLiteral(node) {
12288         var kind = node.kind;
12289         return kind === 211 /* TemplateExpression */
12290             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12291     }
12292     ts.isTemplateLiteral = isTemplateLiteral;
12293     /* @internal */
12294     function isLeftHandSideExpression(node) {
12295         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12296     }
12297     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12298     function isLeftHandSideExpressionKind(kind) {
12299         switch (kind) {
12300             case 194 /* PropertyAccessExpression */:
12301             case 195 /* ElementAccessExpression */:
12302             case 197 /* NewExpression */:
12303             case 196 /* CallExpression */:
12304             case 266 /* JsxElement */:
12305             case 267 /* JsxSelfClosingElement */:
12306             case 270 /* JsxFragment */:
12307             case 198 /* TaggedTemplateExpression */:
12308             case 192 /* ArrayLiteralExpression */:
12309             case 200 /* ParenthesizedExpression */:
12310             case 193 /* ObjectLiteralExpression */:
12311             case 214 /* ClassExpression */:
12312             case 201 /* FunctionExpression */:
12313             case 75 /* Identifier */:
12314             case 13 /* RegularExpressionLiteral */:
12315             case 8 /* NumericLiteral */:
12316             case 9 /* BigIntLiteral */:
12317             case 10 /* StringLiteral */:
12318             case 14 /* NoSubstitutionTemplateLiteral */:
12319             case 211 /* TemplateExpression */:
12320             case 91 /* FalseKeyword */:
12321             case 100 /* NullKeyword */:
12322             case 104 /* ThisKeyword */:
12323             case 106 /* TrueKeyword */:
12324             case 102 /* SuperKeyword */:
12325             case 218 /* NonNullExpression */:
12326             case 219 /* MetaProperty */:
12327             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12328                 return true;
12329             default:
12330                 return false;
12331         }
12332     }
12333     /* @internal */
12334     function isUnaryExpression(node) {
12335         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12336     }
12337     ts.isUnaryExpression = isUnaryExpression;
12338     function isUnaryExpressionKind(kind) {
12339         switch (kind) {
12340             case 207 /* PrefixUnaryExpression */:
12341             case 208 /* PostfixUnaryExpression */:
12342             case 203 /* DeleteExpression */:
12343             case 204 /* TypeOfExpression */:
12344             case 205 /* VoidExpression */:
12345             case 206 /* AwaitExpression */:
12346             case 199 /* TypeAssertionExpression */:
12347                 return true;
12348             default:
12349                 return isLeftHandSideExpressionKind(kind);
12350         }
12351     }
12352     /* @internal */
12353     function isUnaryExpressionWithWrite(expr) {
12354         switch (expr.kind) {
12355             case 208 /* PostfixUnaryExpression */:
12356                 return true;
12357             case 207 /* PrefixUnaryExpression */:
12358                 return expr.operator === 45 /* PlusPlusToken */ ||
12359                     expr.operator === 46 /* MinusMinusToken */;
12360             default:
12361                 return false;
12362         }
12363     }
12364     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12365     /* @internal */
12366     /**
12367      * Determines whether a node is an expression based only on its kind.
12368      * Use `isExpressionNode` if not in transforms.
12369      */
12370     function isExpression(node) {
12371         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12372     }
12373     ts.isExpression = isExpression;
12374     function isExpressionKind(kind) {
12375         switch (kind) {
12376             case 210 /* ConditionalExpression */:
12377             case 212 /* YieldExpression */:
12378             case 202 /* ArrowFunction */:
12379             case 209 /* BinaryExpression */:
12380             case 213 /* SpreadElement */:
12381             case 217 /* AsExpression */:
12382             case 215 /* OmittedExpression */:
12383             case 327 /* CommaListExpression */:
12384             case 326 /* PartiallyEmittedExpression */:
12385                 return true;
12386             default:
12387                 return isUnaryExpressionKind(kind);
12388         }
12389     }
12390     function isAssertionExpression(node) {
12391         var kind = node.kind;
12392         return kind === 199 /* TypeAssertionExpression */
12393             || kind === 217 /* AsExpression */;
12394     }
12395     ts.isAssertionExpression = isAssertionExpression;
12396     /* @internal */
12397     function isPartiallyEmittedExpression(node) {
12398         return node.kind === 326 /* PartiallyEmittedExpression */;
12399     }
12400     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12401     /* @internal */
12402     function isNotEmittedStatement(node) {
12403         return node.kind === 325 /* NotEmittedStatement */;
12404     }
12405     ts.isNotEmittedStatement = isNotEmittedStatement;
12406     /* @internal */
12407     function isSyntheticReference(node) {
12408         return node.kind === 330 /* SyntheticReferenceExpression */;
12409     }
12410     ts.isSyntheticReference = isSyntheticReference;
12411     /* @internal */
12412     function isNotEmittedOrPartiallyEmittedNode(node) {
12413         return isNotEmittedStatement(node)
12414             || isPartiallyEmittedExpression(node);
12415     }
12416     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12417     function isIterationStatement(node, lookInLabeledStatements) {
12418         switch (node.kind) {
12419             case 230 /* ForStatement */:
12420             case 231 /* ForInStatement */:
12421             case 232 /* ForOfStatement */:
12422             case 228 /* DoStatement */:
12423             case 229 /* WhileStatement */:
12424                 return true;
12425             case 238 /* LabeledStatement */:
12426                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12427         }
12428         return false;
12429     }
12430     ts.isIterationStatement = isIterationStatement;
12431     /* @internal */
12432     function isScopeMarker(node) {
12433         return isExportAssignment(node) || isExportDeclaration(node);
12434     }
12435     ts.isScopeMarker = isScopeMarker;
12436     /* @internal */
12437     function hasScopeMarker(statements) {
12438         return ts.some(statements, isScopeMarker);
12439     }
12440     ts.hasScopeMarker = hasScopeMarker;
12441     /* @internal */
12442     function needsScopeMarker(result) {
12443         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12444     }
12445     ts.needsScopeMarker = needsScopeMarker;
12446     /* @internal */
12447     function isExternalModuleIndicator(result) {
12448         // Exported top-level member indicates moduleness
12449         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12450     }
12451     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12452     /* @internal */
12453     function isForInOrOfStatement(node) {
12454         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12455     }
12456     ts.isForInOrOfStatement = isForInOrOfStatement;
12457     // Element
12458     /* @internal */
12459     function isConciseBody(node) {
12460         return isBlock(node)
12461             || isExpression(node);
12462     }
12463     ts.isConciseBody = isConciseBody;
12464     /* @internal */
12465     function isFunctionBody(node) {
12466         return isBlock(node);
12467     }
12468     ts.isFunctionBody = isFunctionBody;
12469     /* @internal */
12470     function isForInitializer(node) {
12471         return isVariableDeclarationList(node)
12472             || isExpression(node);
12473     }
12474     ts.isForInitializer = isForInitializer;
12475     /* @internal */
12476     function isModuleBody(node) {
12477         var kind = node.kind;
12478         return kind === 250 /* ModuleBlock */
12479             || kind === 249 /* ModuleDeclaration */
12480             || kind === 75 /* Identifier */;
12481     }
12482     ts.isModuleBody = isModuleBody;
12483     /* @internal */
12484     function isNamespaceBody(node) {
12485         var kind = node.kind;
12486         return kind === 250 /* ModuleBlock */
12487             || kind === 249 /* ModuleDeclaration */;
12488     }
12489     ts.isNamespaceBody = isNamespaceBody;
12490     /* @internal */
12491     function isJSDocNamespaceBody(node) {
12492         var kind = node.kind;
12493         return kind === 75 /* Identifier */
12494             || kind === 249 /* ModuleDeclaration */;
12495     }
12496     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12497     /* @internal */
12498     function isNamedImportBindings(node) {
12499         var kind = node.kind;
12500         return kind === 257 /* NamedImports */
12501             || kind === 256 /* NamespaceImport */;
12502     }
12503     ts.isNamedImportBindings = isNamedImportBindings;
12504     /* @internal */
12505     function isModuleOrEnumDeclaration(node) {
12506         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12507     }
12508     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12509     function isDeclarationKind(kind) {
12510         return kind === 202 /* ArrowFunction */
12511             || kind === 191 /* BindingElement */
12512             || kind === 245 /* ClassDeclaration */
12513             || kind === 214 /* ClassExpression */
12514             || kind === 162 /* Constructor */
12515             || kind === 248 /* EnumDeclaration */
12516             || kind === 284 /* EnumMember */
12517             || kind === 263 /* ExportSpecifier */
12518             || kind === 244 /* FunctionDeclaration */
12519             || kind === 201 /* FunctionExpression */
12520             || kind === 163 /* GetAccessor */
12521             || kind === 255 /* ImportClause */
12522             || kind === 253 /* ImportEqualsDeclaration */
12523             || kind === 258 /* ImportSpecifier */
12524             || kind === 246 /* InterfaceDeclaration */
12525             || kind === 273 /* JsxAttribute */
12526             || kind === 161 /* MethodDeclaration */
12527             || kind === 160 /* MethodSignature */
12528             || kind === 249 /* ModuleDeclaration */
12529             || kind === 252 /* NamespaceExportDeclaration */
12530             || kind === 256 /* NamespaceImport */
12531             || kind === 262 /* NamespaceExport */
12532             || kind === 156 /* Parameter */
12533             || kind === 281 /* PropertyAssignment */
12534             || kind === 159 /* PropertyDeclaration */
12535             || kind === 158 /* PropertySignature */
12536             || kind === 164 /* SetAccessor */
12537             || kind === 282 /* ShorthandPropertyAssignment */
12538             || kind === 247 /* TypeAliasDeclaration */
12539             || kind === 155 /* TypeParameter */
12540             || kind === 242 /* VariableDeclaration */
12541             || kind === 322 /* JSDocTypedefTag */
12542             || kind === 315 /* JSDocCallbackTag */
12543             || kind === 323 /* JSDocPropertyTag */;
12544     }
12545     function isDeclarationStatementKind(kind) {
12546         return kind === 244 /* FunctionDeclaration */
12547             || kind === 264 /* MissingDeclaration */
12548             || kind === 245 /* ClassDeclaration */
12549             || kind === 246 /* InterfaceDeclaration */
12550             || kind === 247 /* TypeAliasDeclaration */
12551             || kind === 248 /* EnumDeclaration */
12552             || kind === 249 /* ModuleDeclaration */
12553             || kind === 254 /* ImportDeclaration */
12554             || kind === 253 /* ImportEqualsDeclaration */
12555             || kind === 260 /* ExportDeclaration */
12556             || kind === 259 /* ExportAssignment */
12557             || kind === 252 /* NamespaceExportDeclaration */;
12558     }
12559     function isStatementKindButNotDeclarationKind(kind) {
12560         return kind === 234 /* BreakStatement */
12561             || kind === 233 /* ContinueStatement */
12562             || kind === 241 /* DebuggerStatement */
12563             || kind === 228 /* DoStatement */
12564             || kind === 226 /* ExpressionStatement */
12565             || kind === 224 /* EmptyStatement */
12566             || kind === 231 /* ForInStatement */
12567             || kind === 232 /* ForOfStatement */
12568             || kind === 230 /* ForStatement */
12569             || kind === 227 /* IfStatement */
12570             || kind === 238 /* LabeledStatement */
12571             || kind === 235 /* ReturnStatement */
12572             || kind === 237 /* SwitchStatement */
12573             || kind === 239 /* ThrowStatement */
12574             || kind === 240 /* TryStatement */
12575             || kind === 225 /* VariableStatement */
12576             || kind === 229 /* WhileStatement */
12577             || kind === 236 /* WithStatement */
12578             || kind === 325 /* NotEmittedStatement */
12579             || kind === 329 /* EndOfDeclarationMarker */
12580             || kind === 328 /* MergeDeclarationMarker */;
12581     }
12582     /* @internal */
12583     function isDeclaration(node) {
12584         if (node.kind === 155 /* TypeParameter */) {
12585             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12586         }
12587         return isDeclarationKind(node.kind);
12588     }
12589     ts.isDeclaration = isDeclaration;
12590     /* @internal */
12591     function isDeclarationStatement(node) {
12592         return isDeclarationStatementKind(node.kind);
12593     }
12594     ts.isDeclarationStatement = isDeclarationStatement;
12595     /**
12596      * Determines whether the node is a statement that is not also a declaration
12597      */
12598     /* @internal */
12599     function isStatementButNotDeclaration(node) {
12600         return isStatementKindButNotDeclarationKind(node.kind);
12601     }
12602     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12603     /* @internal */
12604     function isStatement(node) {
12605         var kind = node.kind;
12606         return isStatementKindButNotDeclarationKind(kind)
12607             || isDeclarationStatementKind(kind)
12608             || isBlockStatement(node);
12609     }
12610     ts.isStatement = isStatement;
12611     function isBlockStatement(node) {
12612         if (node.kind !== 223 /* Block */)
12613             return false;
12614         if (node.parent !== undefined) {
12615             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12616                 return false;
12617             }
12618         }
12619         return !ts.isFunctionBlock(node);
12620     }
12621     // Module references
12622     /* @internal */
12623     function isModuleReference(node) {
12624         var kind = node.kind;
12625         return kind === 265 /* ExternalModuleReference */
12626             || kind === 153 /* QualifiedName */
12627             || kind === 75 /* Identifier */;
12628     }
12629     ts.isModuleReference = isModuleReference;
12630     // JSX
12631     /* @internal */
12632     function isJsxTagNameExpression(node) {
12633         var kind = node.kind;
12634         return kind === 104 /* ThisKeyword */
12635             || kind === 75 /* Identifier */
12636             || kind === 194 /* PropertyAccessExpression */;
12637     }
12638     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12639     /* @internal */
12640     function isJsxChild(node) {
12641         var kind = node.kind;
12642         return kind === 266 /* JsxElement */
12643             || kind === 276 /* JsxExpression */
12644             || kind === 267 /* JsxSelfClosingElement */
12645             || kind === 11 /* JsxText */
12646             || kind === 270 /* JsxFragment */;
12647     }
12648     ts.isJsxChild = isJsxChild;
12649     /* @internal */
12650     function isJsxAttributeLike(node) {
12651         var kind = node.kind;
12652         return kind === 273 /* JsxAttribute */
12653             || kind === 275 /* JsxSpreadAttribute */;
12654     }
12655     ts.isJsxAttributeLike = isJsxAttributeLike;
12656     /* @internal */
12657     function isStringLiteralOrJsxExpression(node) {
12658         var kind = node.kind;
12659         return kind === 10 /* StringLiteral */
12660             || kind === 276 /* JsxExpression */;
12661     }
12662     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12663     function isJsxOpeningLikeElement(node) {
12664         var kind = node.kind;
12665         return kind === 268 /* JsxOpeningElement */
12666             || kind === 267 /* JsxSelfClosingElement */;
12667     }
12668     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12669     // Clauses
12670     function isCaseOrDefaultClause(node) {
12671         var kind = node.kind;
12672         return kind === 277 /* CaseClause */
12673             || kind === 278 /* DefaultClause */;
12674     }
12675     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12676     // JSDoc
12677     /** True if node is of some JSDoc syntax kind. */
12678     /* @internal */
12679     function isJSDocNode(node) {
12680         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12681     }
12682     ts.isJSDocNode = isJSDocNode;
12683     /** True if node is of a kind that may contain comment text. */
12684     function isJSDocCommentContainingNode(node) {
12685         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12686     }
12687     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12688     // TODO: determine what this does before making it public.
12689     /* @internal */
12690     function isJSDocTag(node) {
12691         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12692     }
12693     ts.isJSDocTag = isJSDocTag;
12694     function isSetAccessor(node) {
12695         return node.kind === 164 /* SetAccessor */;
12696     }
12697     ts.isSetAccessor = isSetAccessor;
12698     function isGetAccessor(node) {
12699         return node.kind === 163 /* GetAccessor */;
12700     }
12701     ts.isGetAccessor = isGetAccessor;
12702     /** True if has jsdoc nodes attached to it. */
12703     /* @internal */
12704     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12705     function hasJSDocNodes(node) {
12706         var jsDoc = node.jsDoc;
12707         return !!jsDoc && jsDoc.length > 0;
12708     }
12709     ts.hasJSDocNodes = hasJSDocNodes;
12710     /** True if has type node attached to it. */
12711     /* @internal */
12712     function hasType(node) {
12713         return !!node.type;
12714     }
12715     ts.hasType = hasType;
12716     /** True if has initializer node attached to it. */
12717     /* @internal */
12718     function hasInitializer(node) {
12719         return !!node.initializer;
12720     }
12721     ts.hasInitializer = hasInitializer;
12722     /** True if has initializer node attached to it. */
12723     function hasOnlyExpressionInitializer(node) {
12724         switch (node.kind) {
12725             case 242 /* VariableDeclaration */:
12726             case 156 /* Parameter */:
12727             case 191 /* BindingElement */:
12728             case 158 /* PropertySignature */:
12729             case 159 /* PropertyDeclaration */:
12730             case 281 /* PropertyAssignment */:
12731             case 284 /* EnumMember */:
12732                 return true;
12733             default:
12734                 return false;
12735         }
12736     }
12737     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12738     function isObjectLiteralElement(node) {
12739         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12740     }
12741     ts.isObjectLiteralElement = isObjectLiteralElement;
12742     /* @internal */
12743     function isTypeReferenceType(node) {
12744         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12745     }
12746     ts.isTypeReferenceType = isTypeReferenceType;
12747     var MAX_SMI_X86 = 1073741823;
12748     /* @internal */
12749     function guessIndentation(lines) {
12750         var indentation = MAX_SMI_X86;
12751         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12752             var line = lines_1[_i];
12753             if (!line.length) {
12754                 continue;
12755             }
12756             var i = 0;
12757             for (; i < line.length && i < indentation; i++) {
12758                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12759                     break;
12760                 }
12761             }
12762             if (i < indentation) {
12763                 indentation = i;
12764             }
12765             if (indentation === 0) {
12766                 return 0;
12767             }
12768         }
12769         return indentation === MAX_SMI_X86 ? undefined : indentation;
12770     }
12771     ts.guessIndentation = guessIndentation;
12772     function isStringLiteralLike(node) {
12773         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12774     }
12775     ts.isStringLiteralLike = isStringLiteralLike;
12776     // #endregion
12777 })(ts || (ts = {}));
12778 /* @internal */
12779 var ts;
12780 (function (ts) {
12781     ts.resolvingEmptyArray = [];
12782     ts.emptyMap = ts.createMap();
12783     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12784     ts.externalHelpersModuleNameText = "tslib";
12785     ts.defaultMaximumTruncationLength = 160;
12786     ts.noTruncationMaximumTruncationLength = 1000000;
12787     function getDeclarationOfKind(symbol, kind) {
12788         var declarations = symbol.declarations;
12789         if (declarations) {
12790             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12791                 var declaration = declarations_1[_i];
12792                 if (declaration.kind === kind) {
12793                     return declaration;
12794                 }
12795             }
12796         }
12797         return undefined;
12798     }
12799     ts.getDeclarationOfKind = getDeclarationOfKind;
12800     /** Create a new escaped identifier map. */
12801     function createUnderscoreEscapedMap() {
12802         return new ts.Map();
12803     }
12804     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12805     function hasEntries(map) {
12806         return !!map && !!map.size;
12807     }
12808     ts.hasEntries = hasEntries;
12809     function createSymbolTable(symbols) {
12810         var result = ts.createMap();
12811         if (symbols) {
12812             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12813                 var symbol = symbols_1[_i];
12814                 result.set(symbol.escapedName, symbol);
12815             }
12816         }
12817         return result;
12818     }
12819     ts.createSymbolTable = createSymbolTable;
12820     function isTransientSymbol(symbol) {
12821         return (symbol.flags & 33554432 /* Transient */) !== 0;
12822     }
12823     ts.isTransientSymbol = isTransientSymbol;
12824     var stringWriter = createSingleLineStringWriter();
12825     function createSingleLineStringWriter() {
12826         var str = "";
12827         var writeText = function (text) { return str += text; };
12828         return {
12829             getText: function () { return str; },
12830             write: writeText,
12831             rawWrite: writeText,
12832             writeKeyword: writeText,
12833             writeOperator: writeText,
12834             writePunctuation: writeText,
12835             writeSpace: writeText,
12836             writeStringLiteral: writeText,
12837             writeLiteral: writeText,
12838             writeParameter: writeText,
12839             writeProperty: writeText,
12840             writeSymbol: function (s, _) { return writeText(s); },
12841             writeTrailingSemicolon: writeText,
12842             writeComment: writeText,
12843             getTextPos: function () { return str.length; },
12844             getLine: function () { return 0; },
12845             getColumn: function () { return 0; },
12846             getIndent: function () { return 0; },
12847             isAtStartOfLine: function () { return false; },
12848             hasTrailingComment: function () { return false; },
12849             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12850             // Completely ignore indentation for string writers.  And map newlines to
12851             // a single space.
12852             writeLine: function () { return str += " "; },
12853             increaseIndent: ts.noop,
12854             decreaseIndent: ts.noop,
12855             clear: function () { return str = ""; },
12856             trackSymbol: ts.noop,
12857             reportInaccessibleThisError: ts.noop,
12858             reportInaccessibleUniqueSymbolError: ts.noop,
12859             reportPrivateInBaseOfClassExpression: ts.noop,
12860         };
12861     }
12862     function changesAffectModuleResolution(oldOptions, newOptions) {
12863         return oldOptions.configFilePath !== newOptions.configFilePath ||
12864             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12865     }
12866     ts.changesAffectModuleResolution = changesAffectModuleResolution;
12867     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12868         return ts.moduleResolutionOptionDeclarations.some(function (o) {
12869             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12870         });
12871     }
12872     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12873     function findAncestor(node, callback) {
12874         while (node) {
12875             var result = callback(node);
12876             if (result === "quit") {
12877                 return undefined;
12878             }
12879             else if (result) {
12880                 return node;
12881             }
12882             node = node.parent;
12883         }
12884         return undefined;
12885     }
12886     ts.findAncestor = findAncestor;
12887     function forEachAncestor(node, callback) {
12888         while (true) {
12889             var res = callback(node);
12890             if (res === "quit")
12891                 return undefined;
12892             if (res !== undefined)
12893                 return res;
12894             if (ts.isSourceFile(node))
12895                 return undefined;
12896             node = node.parent;
12897         }
12898     }
12899     ts.forEachAncestor = forEachAncestor;
12900     function forEachEntry(map, callback) {
12901         var iterator = map.entries();
12902         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12903             var _a = iterResult.value, key = _a[0], value = _a[1];
12904             var result = callback(value, key);
12905             if (result) {
12906                 return result;
12907             }
12908         }
12909         return undefined;
12910     }
12911     ts.forEachEntry = forEachEntry;
12912     function forEachKey(map, callback) {
12913         var iterator = map.keys();
12914         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12915             var result = callback(iterResult.value);
12916             if (result) {
12917                 return result;
12918             }
12919         }
12920         return undefined;
12921     }
12922     ts.forEachKey = forEachKey;
12923     function copyEntries(source, target) {
12924         source.forEach(function (value, key) {
12925             target.set(key, value);
12926         });
12927     }
12928     ts.copyEntries = copyEntries;
12929     function arrayToSet(array, makeKey) {
12930         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
12931     }
12932     ts.arrayToSet = arrayToSet;
12933     function cloneMap(map) {
12934         var clone = ts.createMap();
12935         copyEntries(map, clone);
12936         return clone;
12937     }
12938     ts.cloneMap = cloneMap;
12939     function usingSingleLineStringWriter(action) {
12940         var oldString = stringWriter.getText();
12941         try {
12942             action(stringWriter);
12943             return stringWriter.getText();
12944         }
12945         finally {
12946             stringWriter.clear();
12947             stringWriter.writeKeyword(oldString);
12948         }
12949     }
12950     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12951     function getFullWidth(node) {
12952         return node.end - node.pos;
12953     }
12954     ts.getFullWidth = getFullWidth;
12955     function getResolvedModule(sourceFile, moduleNameText) {
12956         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12957     }
12958     ts.getResolvedModule = getResolvedModule;
12959     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12960         if (!sourceFile.resolvedModules) {
12961             sourceFile.resolvedModules = ts.createMap();
12962         }
12963         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12964     }
12965     ts.setResolvedModule = setResolvedModule;
12966     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12967         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12968             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
12969         }
12970         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12971     }
12972     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12973     function projectReferenceIsEqualTo(oldRef, newRef) {
12974         return oldRef.path === newRef.path &&
12975             !oldRef.prepend === !newRef.prepend &&
12976             !oldRef.circular === !newRef.circular;
12977     }
12978     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12979     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
12980         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
12981             oldResolution.extension === newResolution.extension &&
12982             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
12983             oldResolution.originalPath === newResolution.originalPath &&
12984             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
12985     }
12986     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
12987     function packageIdIsEqual(a, b) {
12988         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
12989     }
12990     function packageIdToString(_a) {
12991         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
12992         var fullName = subModuleName ? name + "/" + subModuleName : name;
12993         return fullName + "@" + version;
12994     }
12995     ts.packageIdToString = packageIdToString;
12996     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
12997         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
12998     }
12999     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13000     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13001         ts.Debug.assert(names.length === newResolutions.length);
13002         for (var i = 0; i < names.length; i++) {
13003             var newResolution = newResolutions[i];
13004             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13005             var changed = oldResolution
13006                 ? !newResolution || !comparer(oldResolution, newResolution)
13007                 : newResolution;
13008             if (changed) {
13009                 return true;
13010             }
13011         }
13012         return false;
13013     }
13014     ts.hasChangesInResolutions = hasChangesInResolutions;
13015     // Returns true if this node contains a parse error anywhere underneath it.
13016     function containsParseError(node) {
13017         aggregateChildData(node);
13018         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13019     }
13020     ts.containsParseError = containsParseError;
13021     function aggregateChildData(node) {
13022         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13023             // A node is considered to contain a parse error if:
13024             //  a) the parser explicitly marked that it had an error
13025             //  b) any of it's children reported that it had an error.
13026             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13027                 ts.forEachChild(node, containsParseError);
13028             // If so, mark ourselves accordingly.
13029             if (thisNodeOrAnySubNodesHasError) {
13030                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13031             }
13032             // Also mark that we've propagated the child information to this node.  This way we can
13033             // always consult the bit directly on this node without needing to check its children
13034             // again.
13035             node.flags |= 524288 /* HasAggregatedChildData */;
13036         }
13037     }
13038     function getSourceFileOfNode(node) {
13039         while (node && node.kind !== 290 /* SourceFile */) {
13040             node = node.parent;
13041         }
13042         return node;
13043     }
13044     ts.getSourceFileOfNode = getSourceFileOfNode;
13045     function isStatementWithLocals(node) {
13046         switch (node.kind) {
13047             case 223 /* Block */:
13048             case 251 /* CaseBlock */:
13049             case 230 /* ForStatement */:
13050             case 231 /* ForInStatement */:
13051             case 232 /* ForOfStatement */:
13052                 return true;
13053         }
13054         return false;
13055     }
13056     ts.isStatementWithLocals = isStatementWithLocals;
13057     function getStartPositionOfLine(line, sourceFile) {
13058         ts.Debug.assert(line >= 0);
13059         return ts.getLineStarts(sourceFile)[line];
13060     }
13061     ts.getStartPositionOfLine = getStartPositionOfLine;
13062     // This is a useful function for debugging purposes.
13063     function nodePosToString(node) {
13064         var file = getSourceFileOfNode(node);
13065         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13066         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13067     }
13068     ts.nodePosToString = nodePosToString;
13069     function getEndLinePosition(line, sourceFile) {
13070         ts.Debug.assert(line >= 0);
13071         var lineStarts = ts.getLineStarts(sourceFile);
13072         var lineIndex = line;
13073         var sourceText = sourceFile.text;
13074         if (lineIndex + 1 === lineStarts.length) {
13075             // last line - return EOF
13076             return sourceText.length - 1;
13077         }
13078         else {
13079             // current line start
13080             var start = lineStarts[lineIndex];
13081             // take the start position of the next line - 1 = it should be some line break
13082             var pos = lineStarts[lineIndex + 1] - 1;
13083             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13084             // walk backwards skipping line breaks, stop the the beginning of current line.
13085             // i.e:
13086             // <some text>
13087             // $ <- end of line for this position should match the start position
13088             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13089                 pos--;
13090             }
13091             return pos;
13092         }
13093     }
13094     ts.getEndLinePosition = getEndLinePosition;
13095     /**
13096      * Returns a value indicating whether a name is unique globally or within the current file.
13097      * 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`.
13098      */
13099     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13100         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13101     }
13102     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13103     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13104     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13105     // in the tree), it is definitely missing. However, a node may be defined, but still be
13106     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13107     // get anything in the source code that it expects at that location. For example:
13108     //
13109     //          let a: ;
13110     //
13111     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13112     // code). So the parser will attempt to parse out a type, and will create an actual node.
13113     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13114     // contained within it.
13115     function nodeIsMissing(node) {
13116         if (node === undefined) {
13117             return true;
13118         }
13119         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13120     }
13121     ts.nodeIsMissing = nodeIsMissing;
13122     function nodeIsPresent(node) {
13123         return !nodeIsMissing(node);
13124     }
13125     ts.nodeIsPresent = nodeIsPresent;
13126     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13127         if (from === undefined || from.length === 0)
13128             return to;
13129         var statementIndex = 0;
13130         // skip all prologue directives to insert at the correct position
13131         for (; statementIndex < to.length; ++statementIndex) {
13132             if (!isPrologueDirective(to[statementIndex])) {
13133                 break;
13134             }
13135         }
13136         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13137         return to;
13138     }
13139     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13140         if (statement === undefined)
13141             return to;
13142         var statementIndex = 0;
13143         // skip all prologue directives to insert at the correct position
13144         for (; statementIndex < to.length; ++statementIndex) {
13145             if (!isPrologueDirective(to[statementIndex])) {
13146                 break;
13147             }
13148         }
13149         to.splice(statementIndex, 0, statement);
13150         return to;
13151     }
13152     function isAnyPrologueDirective(node) {
13153         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13154     }
13155     /**
13156      * Prepends statements to an array while taking care of prologue directives.
13157      */
13158     function insertStatementsAfterStandardPrologue(to, from) {
13159         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13160     }
13161     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13162     function insertStatementsAfterCustomPrologue(to, from) {
13163         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13164     }
13165     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13166     /**
13167      * Prepends statements to an array while taking care of prologue directives.
13168      */
13169     function insertStatementAfterStandardPrologue(to, statement) {
13170         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13171     }
13172     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13173     function insertStatementAfterCustomPrologue(to, statement) {
13174         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13175     }
13176     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13177     /**
13178      * Determine if the given comment is a triple-slash
13179      *
13180      * @return true if the comment is a triple-slash comment else false
13181      */
13182     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13183         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13184         // so that we don't end up computing comment string and doing match for all // comments
13185         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13186             commentPos + 2 < commentEnd &&
13187             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13188             var textSubStr = text.substring(commentPos, commentEnd);
13189             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13190                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13191                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13192                 textSubStr.match(defaultLibReferenceRegEx) ?
13193                 true : false;
13194         }
13195         return false;
13196     }
13197     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13198     function isPinnedComment(text, start) {
13199         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13200             text.charCodeAt(start + 2) === 33 /* exclamation */;
13201     }
13202     ts.isPinnedComment = isPinnedComment;
13203     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13204         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13205             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13206             commentDirective,
13207         ]); }));
13208         var usedLines = ts.createMap();
13209         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13210         function getUnusedExpectations() {
13211             return ts.arrayFrom(directivesByLine.entries())
13212                 .filter(function (_a) {
13213                 var line = _a[0], directive = _a[1];
13214                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13215             })
13216                 .map(function (_a) {
13217                 var _ = _a[0], directive = _a[1];
13218                 return directive;
13219             });
13220         }
13221         function markUsed(line) {
13222             if (!directivesByLine.has("" + line)) {
13223                 return false;
13224             }
13225             usedLines.set("" + line, true);
13226             return true;
13227         }
13228     }
13229     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13230     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13231         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13232         // want to skip trivia because this will launch us forward to the next token.
13233         if (nodeIsMissing(node)) {
13234             return node.pos;
13235         }
13236         if (ts.isJSDocNode(node)) {
13237             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13238         }
13239         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13240             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13241         }
13242         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13243         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13244         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13245         // first child to determine the actual position of its first token.
13246         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13247             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13248         }
13249         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13250     }
13251     ts.getTokenPosOfNode = getTokenPosOfNode;
13252     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13253         if (nodeIsMissing(node) || !node.decorators) {
13254             return getTokenPosOfNode(node, sourceFile);
13255         }
13256         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13257     }
13258     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13259     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13260         if (includeTrivia === void 0) { includeTrivia = false; }
13261         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13262     }
13263     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13264     function isJSDocTypeExpressionOrChild(node) {
13265         return !!findAncestor(node, ts.isJSDocTypeExpression);
13266     }
13267     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13268         if (includeTrivia === void 0) { includeTrivia = false; }
13269         if (nodeIsMissing(node)) {
13270             return "";
13271         }
13272         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13273         if (isJSDocTypeExpressionOrChild(node)) {
13274             // strip space + asterisk at line start
13275             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13276         }
13277         return text;
13278     }
13279     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13280     function getTextOfNode(node, includeTrivia) {
13281         if (includeTrivia === void 0) { includeTrivia = false; }
13282         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13283     }
13284     ts.getTextOfNode = getTextOfNode;
13285     function getPos(range) {
13286         return range.pos;
13287     }
13288     /**
13289      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13290      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13291      */
13292     function indexOfNode(nodeArray, node) {
13293         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13294     }
13295     ts.indexOfNode = indexOfNode;
13296     /**
13297      * Gets flags that control emit behavior of a node.
13298      */
13299     function getEmitFlags(node) {
13300         var emitNode = node.emitNode;
13301         return emitNode && emitNode.flags || 0;
13302     }
13303     ts.getEmitFlags = getEmitFlags;
13304     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13305         // If we don't need to downlevel and we can reach the original source text using
13306         // the node's parent reference, then simply get the text as it was originally written.
13307         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13308             ts.isBigIntLiteral(node))) {
13309             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13310         }
13311         // If we can't reach the original source text, use the canonical form if it's a number,
13312         // or a (possibly escaped) quoted form of the original text if it's string-like.
13313         switch (node.kind) {
13314             case 10 /* StringLiteral */: {
13315                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13316                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13317                         escapeNonAsciiString;
13318                 if (node.singleQuote) {
13319                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13320                 }
13321                 else {
13322                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13323                 }
13324             }
13325             case 14 /* NoSubstitutionTemplateLiteral */:
13326             case 15 /* TemplateHead */:
13327             case 16 /* TemplateMiddle */:
13328             case 17 /* TemplateTail */: {
13329                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13330                 // had to include a backslash: `not \${a} substitution`.
13331                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13332                     escapeNonAsciiString;
13333                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13334                 switch (node.kind) {
13335                     case 14 /* NoSubstitutionTemplateLiteral */:
13336                         return "`" + rawText + "`";
13337                     case 15 /* TemplateHead */:
13338                         return "`" + rawText + "${";
13339                     case 16 /* TemplateMiddle */:
13340                         return "}" + rawText + "${";
13341                     case 17 /* TemplateTail */:
13342                         return "}" + rawText + "`";
13343                 }
13344                 break;
13345             }
13346             case 8 /* NumericLiteral */:
13347             case 9 /* BigIntLiteral */:
13348             case 13 /* RegularExpressionLiteral */:
13349                 return node.text;
13350         }
13351         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13352     }
13353     ts.getLiteralText = getLiteralText;
13354     function getTextOfConstantValue(value) {
13355         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13356     }
13357     ts.getTextOfConstantValue = getTextOfConstantValue;
13358     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13359     // all non-alphanumeric characters with underscores
13360     function makeIdentifierFromModuleName(moduleName) {
13361         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13362     }
13363     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13364     function isBlockOrCatchScoped(declaration) {
13365         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13366             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13367     }
13368     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13369     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13370         var node = getRootDeclaration(declaration);
13371         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13372     }
13373     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13374     function isAmbientModule(node) {
13375         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13376     }
13377     ts.isAmbientModule = isAmbientModule;
13378     function isModuleWithStringLiteralName(node) {
13379         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13380     }
13381     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13382     function isNonGlobalAmbientModule(node) {
13383         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13384     }
13385     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13386     /**
13387      * An effective module (namespace) declaration is either
13388      * 1. An actual declaration: namespace X { ... }
13389      * 2. A Javascript declaration, which is:
13390      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13391      */
13392     function isEffectiveModuleDeclaration(node) {
13393         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13394     }
13395     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13396     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13397     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13398         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13399     }
13400     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13401     function isShorthandAmbientModule(node) {
13402         // The only kind of module that can be missing a body is a shorthand ambient module.
13403         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13404     }
13405     function isBlockScopedContainerTopLevel(node) {
13406         return node.kind === 290 /* SourceFile */ ||
13407             node.kind === 249 /* ModuleDeclaration */ ||
13408             ts.isFunctionLike(node);
13409     }
13410     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13411     function isGlobalScopeAugmentation(module) {
13412         return !!(module.flags & 1024 /* GlobalAugmentation */);
13413     }
13414     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13415     function isExternalModuleAugmentation(node) {
13416         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13417     }
13418     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13419     function isModuleAugmentationExternal(node) {
13420         // external module augmentation is a ambient module declaration that is either:
13421         // - defined in the top level scope and source file is an external module
13422         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13423         switch (node.parent.kind) {
13424             case 290 /* SourceFile */:
13425                 return ts.isExternalModule(node.parent);
13426             case 250 /* ModuleBlock */:
13427                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13428         }
13429         return false;
13430     }
13431     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13432     function getNonAugmentationDeclaration(symbol) {
13433         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13434     }
13435     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13436     function isEffectiveExternalModule(node, compilerOptions) {
13437         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13438     }
13439     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13440     /**
13441      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13442      */
13443     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13444         // We can only verify strict mode for JS/TS files
13445         switch (node.scriptKind) {
13446             case 1 /* JS */:
13447             case 3 /* TS */:
13448             case 2 /* JSX */:
13449             case 4 /* TSX */:
13450                 break;
13451             default:
13452                 return false;
13453         }
13454         // Strict mode does not matter for declaration files.
13455         if (node.isDeclarationFile) {
13456             return false;
13457         }
13458         // If `alwaysStrict` is set, then treat the file as strict.
13459         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13460             return true;
13461         }
13462         // Starting with a "use strict" directive indicates the file is strict.
13463         if (ts.startsWithUseStrict(node.statements)) {
13464             return true;
13465         }
13466         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13467             // ECMAScript Modules are always strict.
13468             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13469                 return true;
13470             }
13471             // Other modules are strict unless otherwise specified.
13472             return !compilerOptions.noImplicitUseStrict;
13473         }
13474         return false;
13475     }
13476     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13477     function isBlockScope(node, parentNode) {
13478         switch (node.kind) {
13479             case 290 /* SourceFile */:
13480             case 251 /* CaseBlock */:
13481             case 280 /* CatchClause */:
13482             case 249 /* ModuleDeclaration */:
13483             case 230 /* ForStatement */:
13484             case 231 /* ForInStatement */:
13485             case 232 /* ForOfStatement */:
13486             case 162 /* Constructor */:
13487             case 161 /* MethodDeclaration */:
13488             case 163 /* GetAccessor */:
13489             case 164 /* SetAccessor */:
13490             case 244 /* FunctionDeclaration */:
13491             case 201 /* FunctionExpression */:
13492             case 202 /* ArrowFunction */:
13493                 return true;
13494             case 223 /* Block */:
13495                 // function block is not considered block-scope container
13496                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13497                 return !ts.isFunctionLike(parentNode);
13498         }
13499         return false;
13500     }
13501     ts.isBlockScope = isBlockScope;
13502     function isDeclarationWithTypeParameters(node) {
13503         switch (node.kind) {
13504             case 315 /* JSDocCallbackTag */:
13505             case 322 /* JSDocTypedefTag */:
13506             case 305 /* JSDocSignature */:
13507                 return true;
13508             default:
13509                 ts.assertType(node);
13510                 return isDeclarationWithTypeParameterChildren(node);
13511         }
13512     }
13513     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13514     function isDeclarationWithTypeParameterChildren(node) {
13515         switch (node.kind) {
13516             case 165 /* CallSignature */:
13517             case 166 /* ConstructSignature */:
13518             case 160 /* MethodSignature */:
13519             case 167 /* IndexSignature */:
13520             case 170 /* FunctionType */:
13521             case 171 /* ConstructorType */:
13522             case 300 /* JSDocFunctionType */:
13523             case 245 /* ClassDeclaration */:
13524             case 214 /* ClassExpression */:
13525             case 246 /* InterfaceDeclaration */:
13526             case 247 /* TypeAliasDeclaration */:
13527             case 321 /* JSDocTemplateTag */:
13528             case 244 /* FunctionDeclaration */:
13529             case 161 /* MethodDeclaration */:
13530             case 162 /* Constructor */:
13531             case 163 /* GetAccessor */:
13532             case 164 /* SetAccessor */:
13533             case 201 /* FunctionExpression */:
13534             case 202 /* ArrowFunction */:
13535                 return true;
13536             default:
13537                 ts.assertType(node);
13538                 return false;
13539         }
13540     }
13541     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13542     function isAnyImportSyntax(node) {
13543         switch (node.kind) {
13544             case 254 /* ImportDeclaration */:
13545             case 253 /* ImportEqualsDeclaration */:
13546                 return true;
13547             default:
13548                 return false;
13549         }
13550     }
13551     ts.isAnyImportSyntax = isAnyImportSyntax;
13552     function isLateVisibilityPaintedStatement(node) {
13553         switch (node.kind) {
13554             case 254 /* ImportDeclaration */:
13555             case 253 /* ImportEqualsDeclaration */:
13556             case 225 /* VariableStatement */:
13557             case 245 /* ClassDeclaration */:
13558             case 244 /* FunctionDeclaration */:
13559             case 249 /* ModuleDeclaration */:
13560             case 247 /* TypeAliasDeclaration */:
13561             case 246 /* InterfaceDeclaration */:
13562             case 248 /* EnumDeclaration */:
13563                 return true;
13564             default:
13565                 return false;
13566         }
13567     }
13568     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13569     function isAnyImportOrReExport(node) {
13570         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13571     }
13572     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13573     // Gets the nearest enclosing block scope container that has the provided node
13574     // as a descendant, that is not the provided node.
13575     function getEnclosingBlockScopeContainer(node) {
13576         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13577     }
13578     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13579     // Return display name of an identifier
13580     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13581     // text of the expression in the computed property.
13582     function declarationNameToString(name) {
13583         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13584     }
13585     ts.declarationNameToString = declarationNameToString;
13586     function getNameFromIndexInfo(info) {
13587         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13588     }
13589     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13590     function isComputedNonLiteralName(name) {
13591         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13592     }
13593     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13594     function getTextOfPropertyName(name) {
13595         switch (name.kind) {
13596             case 75 /* Identifier */:
13597             case 76 /* PrivateIdentifier */:
13598                 return name.escapedText;
13599             case 10 /* StringLiteral */:
13600             case 8 /* NumericLiteral */:
13601             case 14 /* NoSubstitutionTemplateLiteral */:
13602                 return ts.escapeLeadingUnderscores(name.text);
13603             case 154 /* ComputedPropertyName */:
13604                 if (isStringOrNumericLiteralLike(name.expression))
13605                     return ts.escapeLeadingUnderscores(name.expression.text);
13606                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13607             default:
13608                 return ts.Debug.assertNever(name);
13609         }
13610     }
13611     ts.getTextOfPropertyName = getTextOfPropertyName;
13612     function entityNameToString(name) {
13613         switch (name.kind) {
13614             case 104 /* ThisKeyword */:
13615                 return "this";
13616             case 76 /* PrivateIdentifier */:
13617             case 75 /* Identifier */:
13618                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13619             case 153 /* QualifiedName */:
13620                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13621             case 194 /* PropertyAccessExpression */:
13622                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13623                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13624                 }
13625                 else {
13626                     return ts.Debug.assertNever(name.name);
13627                 }
13628             default:
13629                 return ts.Debug.assertNever(name);
13630         }
13631     }
13632     ts.entityNameToString = entityNameToString;
13633     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13634         var sourceFile = getSourceFileOfNode(node);
13635         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13636     }
13637     ts.createDiagnosticForNode = createDiagnosticForNode;
13638     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13639         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13640         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13641     }
13642     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13643     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13644         var span = getErrorSpanForNode(sourceFile, node);
13645         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13646     }
13647     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13648     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13649         var sourceFile = getSourceFileOfNode(node);
13650         var span = getErrorSpanForNode(sourceFile, node);
13651         return {
13652             file: sourceFile,
13653             start: span.start,
13654             length: span.length,
13655             code: messageChain.code,
13656             category: messageChain.category,
13657             messageText: messageChain.next ? messageChain : messageChain.messageText,
13658             relatedInformation: relatedInformation
13659         };
13660     }
13661     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13662     function createDiagnosticForRange(sourceFile, range, message) {
13663         return {
13664             file: sourceFile,
13665             start: range.pos,
13666             length: range.end - range.pos,
13667             code: message.code,
13668             category: message.category,
13669             messageText: message.message,
13670         };
13671     }
13672     ts.createDiagnosticForRange = createDiagnosticForRange;
13673     function getSpanOfTokenAtPosition(sourceFile, pos) {
13674         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13675         scanner.scan();
13676         var start = scanner.getTokenPos();
13677         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13678     }
13679     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13680     function getErrorSpanForArrowFunction(sourceFile, node) {
13681         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13682         if (node.body && node.body.kind === 223 /* Block */) {
13683             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13684             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13685             if (startLine < endLine) {
13686                 // The arrow function spans multiple lines,
13687                 // make the error span be the first line, inclusive.
13688                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13689             }
13690         }
13691         return ts.createTextSpanFromBounds(pos, node.end);
13692     }
13693     function getErrorSpanForNode(sourceFile, node) {
13694         var errorNode = node;
13695         switch (node.kind) {
13696             case 290 /* SourceFile */:
13697                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13698                 if (pos_1 === sourceFile.text.length) {
13699                     // file is empty - return span for the beginning of the file
13700                     return ts.createTextSpan(0, 0);
13701                 }
13702                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13703             // This list is a work in progress. Add missing node kinds to improve their error
13704             // spans.
13705             case 242 /* VariableDeclaration */:
13706             case 191 /* BindingElement */:
13707             case 245 /* ClassDeclaration */:
13708             case 214 /* ClassExpression */:
13709             case 246 /* InterfaceDeclaration */:
13710             case 249 /* ModuleDeclaration */:
13711             case 248 /* EnumDeclaration */:
13712             case 284 /* EnumMember */:
13713             case 244 /* FunctionDeclaration */:
13714             case 201 /* FunctionExpression */:
13715             case 161 /* MethodDeclaration */:
13716             case 163 /* GetAccessor */:
13717             case 164 /* SetAccessor */:
13718             case 247 /* TypeAliasDeclaration */:
13719             case 159 /* PropertyDeclaration */:
13720             case 158 /* PropertySignature */:
13721                 errorNode = node.name;
13722                 break;
13723             case 202 /* ArrowFunction */:
13724                 return getErrorSpanForArrowFunction(sourceFile, node);
13725             case 277 /* CaseClause */:
13726             case 278 /* DefaultClause */:
13727                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13728                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13729                 return ts.createTextSpanFromBounds(start, end);
13730         }
13731         if (errorNode === undefined) {
13732             // If we don't have a better node, then just set the error on the first token of
13733             // construct.
13734             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13735         }
13736         ts.Debug.assert(!ts.isJSDoc(errorNode));
13737         var isMissing = nodeIsMissing(errorNode);
13738         var pos = isMissing || ts.isJsxText(node)
13739             ? errorNode.pos
13740             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13741         // These asserts should all be satisfied for a properly constructed `errorNode`.
13742         if (isMissing) {
13743             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13744             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13745         }
13746         else {
13747             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13748             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13749         }
13750         return ts.createTextSpanFromBounds(pos, errorNode.end);
13751     }
13752     ts.getErrorSpanForNode = getErrorSpanForNode;
13753     function isExternalOrCommonJsModule(file) {
13754         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13755     }
13756     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13757     function isJsonSourceFile(file) {
13758         return file.scriptKind === 6 /* JSON */;
13759     }
13760     ts.isJsonSourceFile = isJsonSourceFile;
13761     function isEnumConst(node) {
13762         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13763     }
13764     ts.isEnumConst = isEnumConst;
13765     function isDeclarationReadonly(declaration) {
13766         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13767     }
13768     ts.isDeclarationReadonly = isDeclarationReadonly;
13769     function isVarConst(node) {
13770         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13771     }
13772     ts.isVarConst = isVarConst;
13773     function isLet(node) {
13774         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13775     }
13776     ts.isLet = isLet;
13777     function isSuperCall(n) {
13778         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13779     }
13780     ts.isSuperCall = isSuperCall;
13781     function isImportCall(n) {
13782         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13783     }
13784     ts.isImportCall = isImportCall;
13785     function isImportMeta(n) {
13786         return ts.isMetaProperty(n)
13787             && n.keywordToken === 96 /* ImportKeyword */
13788             && n.name.escapedText === "meta";
13789     }
13790     ts.isImportMeta = isImportMeta;
13791     function isLiteralImportTypeNode(n) {
13792         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13793     }
13794     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13795     function isPrologueDirective(node) {
13796         return node.kind === 226 /* ExpressionStatement */
13797             && node.expression.kind === 10 /* StringLiteral */;
13798     }
13799     ts.isPrologueDirective = isPrologueDirective;
13800     function isCustomPrologue(node) {
13801         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13802     }
13803     ts.isCustomPrologue = isCustomPrologue;
13804     function isHoistedFunction(node) {
13805         return isCustomPrologue(node)
13806             && ts.isFunctionDeclaration(node);
13807     }
13808     ts.isHoistedFunction = isHoistedFunction;
13809     function isHoistedVariable(node) {
13810         return ts.isIdentifier(node.name)
13811             && !node.initializer;
13812     }
13813     function isHoistedVariableStatement(node) {
13814         return isCustomPrologue(node)
13815             && ts.isVariableStatement(node)
13816             && ts.every(node.declarationList.declarations, isHoistedVariable);
13817     }
13818     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13819     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13820         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13821     }
13822     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13823     function getJSDocCommentRanges(node, text) {
13824         var commentRanges = (node.kind === 156 /* Parameter */ ||
13825             node.kind === 155 /* TypeParameter */ ||
13826             node.kind === 201 /* FunctionExpression */ ||
13827             node.kind === 202 /* ArrowFunction */ ||
13828             node.kind === 200 /* ParenthesizedExpression */) ?
13829             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13830             ts.getLeadingCommentRanges(text, node.pos);
13831         // True if the comment starts with '/**' but not if it is '/**/'
13832         return ts.filter(commentRanges, function (comment) {
13833             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13834                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13835                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13836         });
13837     }
13838     ts.getJSDocCommentRanges = getJSDocCommentRanges;
13839     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13840     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13841     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13842     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13843     function isPartOfTypeNode(node) {
13844         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
13845             return true;
13846         }
13847         switch (node.kind) {
13848             case 125 /* AnyKeyword */:
13849             case 148 /* UnknownKeyword */:
13850             case 140 /* NumberKeyword */:
13851             case 151 /* BigIntKeyword */:
13852             case 143 /* StringKeyword */:
13853             case 128 /* BooleanKeyword */:
13854             case 144 /* SymbolKeyword */:
13855             case 141 /* ObjectKeyword */:
13856             case 146 /* UndefinedKeyword */:
13857             case 137 /* NeverKeyword */:
13858                 return true;
13859             case 110 /* VoidKeyword */:
13860                 return node.parent.kind !== 205 /* VoidExpression */;
13861             case 216 /* ExpressionWithTypeArguments */:
13862                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13863             case 155 /* TypeParameter */:
13864                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
13865             // Identifiers and qualified names may be type nodes, depending on their context. Climb
13866             // above them to find the lowest container
13867             case 75 /* Identifier */:
13868                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13869                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
13870                     node = node.parent;
13871                 }
13872                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
13873                     node = node.parent;
13874                 }
13875                 // At this point, node is either a qualified name or an identifier
13876                 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'.");
13877             // falls through
13878             case 153 /* QualifiedName */:
13879             case 194 /* PropertyAccessExpression */:
13880             case 104 /* ThisKeyword */: {
13881                 var parent = node.parent;
13882                 if (parent.kind === 172 /* TypeQuery */) {
13883                     return false;
13884                 }
13885                 if (parent.kind === 188 /* ImportType */) {
13886                     return !parent.isTypeOf;
13887                 }
13888                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13889                 //
13890                 //     let a: A.B.C;
13891                 //
13892                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13893                 // Only C and A.B.C are type nodes.
13894                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
13895                     return true;
13896                 }
13897                 switch (parent.kind) {
13898                     case 216 /* ExpressionWithTypeArguments */:
13899                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13900                     case 155 /* TypeParameter */:
13901                         return node === parent.constraint;
13902                     case 321 /* JSDocTemplateTag */:
13903                         return node === parent.constraint;
13904                     case 159 /* PropertyDeclaration */:
13905                     case 158 /* PropertySignature */:
13906                     case 156 /* Parameter */:
13907                     case 242 /* VariableDeclaration */:
13908                         return node === parent.type;
13909                     case 244 /* FunctionDeclaration */:
13910                     case 201 /* FunctionExpression */:
13911                     case 202 /* ArrowFunction */:
13912                     case 162 /* Constructor */:
13913                     case 161 /* MethodDeclaration */:
13914                     case 160 /* MethodSignature */:
13915                     case 163 /* GetAccessor */:
13916                     case 164 /* SetAccessor */:
13917                         return node === parent.type;
13918                     case 165 /* CallSignature */:
13919                     case 166 /* ConstructSignature */:
13920                     case 167 /* IndexSignature */:
13921                         return node === parent.type;
13922                     case 199 /* TypeAssertionExpression */:
13923                         return node === parent.type;
13924                     case 196 /* CallExpression */:
13925                     case 197 /* NewExpression */:
13926                         return ts.contains(parent.typeArguments, node);
13927                     case 198 /* TaggedTemplateExpression */:
13928                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13929                         return false;
13930                 }
13931             }
13932         }
13933         return false;
13934     }
13935     ts.isPartOfTypeNode = isPartOfTypeNode;
13936     function isChildOfNodeWithKind(node, kind) {
13937         while (node) {
13938             if (node.kind === kind) {
13939                 return true;
13940             }
13941             node = node.parent;
13942         }
13943         return false;
13944     }
13945     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13946     // Warning: This has the same semantics as the forEach family of functions,
13947     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
13948     function forEachReturnStatement(body, visitor) {
13949         return traverse(body);
13950         function traverse(node) {
13951             switch (node.kind) {
13952                 case 235 /* ReturnStatement */:
13953                     return visitor(node);
13954                 case 251 /* CaseBlock */:
13955                 case 223 /* Block */:
13956                 case 227 /* IfStatement */:
13957                 case 228 /* DoStatement */:
13958                 case 229 /* WhileStatement */:
13959                 case 230 /* ForStatement */:
13960                 case 231 /* ForInStatement */:
13961                 case 232 /* ForOfStatement */:
13962                 case 236 /* WithStatement */:
13963                 case 237 /* SwitchStatement */:
13964                 case 277 /* CaseClause */:
13965                 case 278 /* DefaultClause */:
13966                 case 238 /* LabeledStatement */:
13967                 case 240 /* TryStatement */:
13968                 case 280 /* CatchClause */:
13969                     return ts.forEachChild(node, traverse);
13970             }
13971         }
13972     }
13973     ts.forEachReturnStatement = forEachReturnStatement;
13974     function forEachYieldExpression(body, visitor) {
13975         return traverse(body);
13976         function traverse(node) {
13977             switch (node.kind) {
13978                 case 212 /* YieldExpression */:
13979                     visitor(node);
13980                     var operand = node.expression;
13981                     if (operand) {
13982                         traverse(operand);
13983                     }
13984                     return;
13985                 case 248 /* EnumDeclaration */:
13986                 case 246 /* InterfaceDeclaration */:
13987                 case 249 /* ModuleDeclaration */:
13988                 case 247 /* TypeAliasDeclaration */:
13989                     // These are not allowed inside a generator now, but eventually they may be allowed
13990                     // as local types. Regardless, skip them to avoid the work.
13991                     return;
13992                 default:
13993                     if (ts.isFunctionLike(node)) {
13994                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
13995                             // Note that we will not include methods/accessors of a class because they would require
13996                             // first descending into the class. This is by design.
13997                             traverse(node.name.expression);
13998                             return;
13999                         }
14000                     }
14001                     else if (!isPartOfTypeNode(node)) {
14002                         // This is the general case, which should include mostly expressions and statements.
14003                         // Also includes NodeArrays.
14004                         ts.forEachChild(node, traverse);
14005                     }
14006             }
14007         }
14008     }
14009     ts.forEachYieldExpression = forEachYieldExpression;
14010     /**
14011      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14012      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14013      *
14014      * @param node The type node.
14015      */
14016     function getRestParameterElementType(node) {
14017         if (node && node.kind === 174 /* ArrayType */) {
14018             return node.elementType;
14019         }
14020         else if (node && node.kind === 169 /* TypeReference */) {
14021             return ts.singleOrUndefined(node.typeArguments);
14022         }
14023         else {
14024             return undefined;
14025         }
14026     }
14027     ts.getRestParameterElementType = getRestParameterElementType;
14028     function getMembersOfDeclaration(node) {
14029         switch (node.kind) {
14030             case 246 /* InterfaceDeclaration */:
14031             case 245 /* ClassDeclaration */:
14032             case 214 /* ClassExpression */:
14033             case 173 /* TypeLiteral */:
14034                 return node.members;
14035             case 193 /* ObjectLiteralExpression */:
14036                 return node.properties;
14037         }
14038     }
14039     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14040     function isVariableLike(node) {
14041         if (node) {
14042             switch (node.kind) {
14043                 case 191 /* BindingElement */:
14044                 case 284 /* EnumMember */:
14045                 case 156 /* Parameter */:
14046                 case 281 /* PropertyAssignment */:
14047                 case 159 /* PropertyDeclaration */:
14048                 case 158 /* PropertySignature */:
14049                 case 282 /* ShorthandPropertyAssignment */:
14050                 case 242 /* VariableDeclaration */:
14051                     return true;
14052             }
14053         }
14054         return false;
14055     }
14056     ts.isVariableLike = isVariableLike;
14057     function isVariableLikeOrAccessor(node) {
14058         return isVariableLike(node) || ts.isAccessor(node);
14059     }
14060     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14061     function isVariableDeclarationInVariableStatement(node) {
14062         return node.parent.kind === 243 /* VariableDeclarationList */
14063             && node.parent.parent.kind === 225 /* VariableStatement */;
14064     }
14065     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14066     function isValidESSymbolDeclaration(node) {
14067         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14068             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14069                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14070     }
14071     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14072     function introducesArgumentsExoticObject(node) {
14073         switch (node.kind) {
14074             case 161 /* MethodDeclaration */:
14075             case 160 /* MethodSignature */:
14076             case 162 /* Constructor */:
14077             case 163 /* GetAccessor */:
14078             case 164 /* SetAccessor */:
14079             case 244 /* FunctionDeclaration */:
14080             case 201 /* FunctionExpression */:
14081                 return true;
14082         }
14083         return false;
14084     }
14085     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14086     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14087         while (true) {
14088             if (beforeUnwrapLabelCallback) {
14089                 beforeUnwrapLabelCallback(node);
14090             }
14091             if (node.statement.kind !== 238 /* LabeledStatement */) {
14092                 return node.statement;
14093             }
14094             node = node.statement;
14095         }
14096     }
14097     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14098     function isFunctionBlock(node) {
14099         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14100     }
14101     ts.isFunctionBlock = isFunctionBlock;
14102     function isObjectLiteralMethod(node) {
14103         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14104     }
14105     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14106     function isObjectLiteralOrClassExpressionMethod(node) {
14107         return node.kind === 161 /* MethodDeclaration */ &&
14108             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14109                 node.parent.kind === 214 /* ClassExpression */);
14110     }
14111     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14112     function isIdentifierTypePredicate(predicate) {
14113         return predicate && predicate.kind === 1 /* Identifier */;
14114     }
14115     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14116     function isThisTypePredicate(predicate) {
14117         return predicate && predicate.kind === 0 /* This */;
14118     }
14119     ts.isThisTypePredicate = isThisTypePredicate;
14120     function getPropertyAssignment(objectLiteral, key, key2) {
14121         return objectLiteral.properties.filter(function (property) {
14122             if (property.kind === 281 /* PropertyAssignment */) {
14123                 var propName = getTextOfPropertyName(property.name);
14124                 return key === propName || (!!key2 && key2 === propName);
14125             }
14126             return false;
14127         });
14128     }
14129     ts.getPropertyAssignment = getPropertyAssignment;
14130     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14131         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14132             var expression = tsConfigSourceFile.statements[0].expression;
14133             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14134         }
14135     }
14136     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14137     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14138         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14139             return ts.isArrayLiteralExpression(property.initializer) ?
14140                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14141                 undefined;
14142         });
14143     }
14144     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14145     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14146         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14147         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14148     }
14149     ts.getTsConfigPropArray = getTsConfigPropArray;
14150     function getContainingFunction(node) {
14151         return findAncestor(node.parent, ts.isFunctionLike);
14152     }
14153     ts.getContainingFunction = getContainingFunction;
14154     function getContainingFunctionDeclaration(node) {
14155         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14156     }
14157     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14158     function getContainingClass(node) {
14159         return findAncestor(node.parent, ts.isClassLike);
14160     }
14161     ts.getContainingClass = getContainingClass;
14162     function getThisContainer(node, includeArrowFunctions) {
14163         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14164         while (true) {
14165             node = node.parent;
14166             if (!node) {
14167                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14168             }
14169             switch (node.kind) {
14170                 case 154 /* ComputedPropertyName */:
14171                     // If the grandparent node is an object literal (as opposed to a class),
14172                     // then the computed property is not a 'this' container.
14173                     // A computed property name in a class needs to be a this container
14174                     // so that we can error on it.
14175                     if (ts.isClassLike(node.parent.parent)) {
14176                         return node;
14177                     }
14178                     // If this is a computed property, then the parent should not
14179                     // make it a this container. The parent might be a property
14180                     // in an object literal, like a method or accessor. But in order for
14181                     // such a parent to be a this container, the reference must be in
14182                     // the *body* of the container.
14183                     node = node.parent;
14184                     break;
14185                 case 157 /* Decorator */:
14186                     // Decorators are always applied outside of the body of a class or method.
14187                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14188                         // If the decorator's parent is a Parameter, we resolve the this container from
14189                         // the grandparent class declaration.
14190                         node = node.parent.parent;
14191                     }
14192                     else if (ts.isClassElement(node.parent)) {
14193                         // If the decorator's parent is a class element, we resolve the 'this' container
14194                         // from the parent class declaration.
14195                         node = node.parent;
14196                     }
14197                     break;
14198                 case 202 /* ArrowFunction */:
14199                     if (!includeArrowFunctions) {
14200                         continue;
14201                     }
14202                 // falls through
14203                 case 244 /* FunctionDeclaration */:
14204                 case 201 /* FunctionExpression */:
14205                 case 249 /* ModuleDeclaration */:
14206                 case 159 /* PropertyDeclaration */:
14207                 case 158 /* PropertySignature */:
14208                 case 161 /* MethodDeclaration */:
14209                 case 160 /* MethodSignature */:
14210                 case 162 /* Constructor */:
14211                 case 163 /* GetAccessor */:
14212                 case 164 /* SetAccessor */:
14213                 case 165 /* CallSignature */:
14214                 case 166 /* ConstructSignature */:
14215                 case 167 /* IndexSignature */:
14216                 case 248 /* EnumDeclaration */:
14217                 case 290 /* SourceFile */:
14218                     return node;
14219             }
14220         }
14221     }
14222     ts.getThisContainer = getThisContainer;
14223     function getNewTargetContainer(node) {
14224         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14225         if (container) {
14226             switch (container.kind) {
14227                 case 162 /* Constructor */:
14228                 case 244 /* FunctionDeclaration */:
14229                 case 201 /* FunctionExpression */:
14230                     return container;
14231             }
14232         }
14233         return undefined;
14234     }
14235     ts.getNewTargetContainer = getNewTargetContainer;
14236     /**
14237      * Given an super call/property node, returns the closest node where
14238      * - a super call/property access is legal in the node and not legal in the parent node the node.
14239      *   i.e. super call is legal in constructor but not legal in the class body.
14240      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14241      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14242      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14243      */
14244     function getSuperContainer(node, stopOnFunctions) {
14245         while (true) {
14246             node = node.parent;
14247             if (!node) {
14248                 return node;
14249             }
14250             switch (node.kind) {
14251                 case 154 /* ComputedPropertyName */:
14252                     node = node.parent;
14253                     break;
14254                 case 244 /* FunctionDeclaration */:
14255                 case 201 /* FunctionExpression */:
14256                 case 202 /* ArrowFunction */:
14257                     if (!stopOnFunctions) {
14258                         continue;
14259                     }
14260                 // falls through
14261                 case 159 /* PropertyDeclaration */:
14262                 case 158 /* PropertySignature */:
14263                 case 161 /* MethodDeclaration */:
14264                 case 160 /* MethodSignature */:
14265                 case 162 /* Constructor */:
14266                 case 163 /* GetAccessor */:
14267                 case 164 /* SetAccessor */:
14268                     return node;
14269                 case 157 /* Decorator */:
14270                     // Decorators are always applied outside of the body of a class or method.
14271                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14272                         // If the decorator's parent is a Parameter, we resolve the this container from
14273                         // the grandparent class declaration.
14274                         node = node.parent.parent;
14275                     }
14276                     else if (ts.isClassElement(node.parent)) {
14277                         // If the decorator's parent is a class element, we resolve the 'this' container
14278                         // from the parent class declaration.
14279                         node = node.parent;
14280                     }
14281                     break;
14282             }
14283         }
14284     }
14285     ts.getSuperContainer = getSuperContainer;
14286     function getImmediatelyInvokedFunctionExpression(func) {
14287         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14288             var prev = func;
14289             var parent = func.parent;
14290             while (parent.kind === 200 /* ParenthesizedExpression */) {
14291                 prev = parent;
14292                 parent = parent.parent;
14293             }
14294             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14295                 return parent;
14296             }
14297         }
14298     }
14299     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14300     function isSuperOrSuperProperty(node) {
14301         return node.kind === 102 /* SuperKeyword */
14302             || isSuperProperty(node);
14303     }
14304     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14305     /**
14306      * Determines whether a node is a property or element access expression for `super`.
14307      */
14308     function isSuperProperty(node) {
14309         var kind = node.kind;
14310         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14311             && node.expression.kind === 102 /* SuperKeyword */;
14312     }
14313     ts.isSuperProperty = isSuperProperty;
14314     /**
14315      * Determines whether a node is a property or element access expression for `this`.
14316      */
14317     function isThisProperty(node) {
14318         var kind = node.kind;
14319         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14320             && node.expression.kind === 104 /* ThisKeyword */;
14321     }
14322     ts.isThisProperty = isThisProperty;
14323     function getEntityNameFromTypeNode(node) {
14324         switch (node.kind) {
14325             case 169 /* TypeReference */:
14326                 return node.typeName;
14327             case 216 /* ExpressionWithTypeArguments */:
14328                 return isEntityNameExpression(node.expression)
14329                     ? node.expression
14330                     : undefined;
14331             case 75 /* Identifier */:
14332             case 153 /* QualifiedName */:
14333                 return node;
14334         }
14335         return undefined;
14336     }
14337     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14338     function getInvokedExpression(node) {
14339         switch (node.kind) {
14340             case 198 /* TaggedTemplateExpression */:
14341                 return node.tag;
14342             case 268 /* JsxOpeningElement */:
14343             case 267 /* JsxSelfClosingElement */:
14344                 return node.tagName;
14345             default:
14346                 return node.expression;
14347         }
14348     }
14349     ts.getInvokedExpression = getInvokedExpression;
14350     function nodeCanBeDecorated(node, parent, grandparent) {
14351         // private names cannot be used with decorators yet
14352         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14353             return false;
14354         }
14355         switch (node.kind) {
14356             case 245 /* ClassDeclaration */:
14357                 // classes are valid targets
14358                 return true;
14359             case 159 /* PropertyDeclaration */:
14360                 // property declarations are valid if their parent is a class declaration.
14361                 return parent.kind === 245 /* ClassDeclaration */;
14362             case 163 /* GetAccessor */:
14363             case 164 /* SetAccessor */:
14364             case 161 /* MethodDeclaration */:
14365                 // if this method has a body and its parent is a class declaration, this is a valid target.
14366                 return node.body !== undefined
14367                     && parent.kind === 245 /* ClassDeclaration */;
14368             case 156 /* Parameter */:
14369                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14370                 return parent.body !== undefined
14371                     && (parent.kind === 162 /* Constructor */
14372                         || parent.kind === 161 /* MethodDeclaration */
14373                         || parent.kind === 164 /* SetAccessor */)
14374                     && grandparent.kind === 245 /* ClassDeclaration */;
14375         }
14376         return false;
14377     }
14378     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14379     function nodeIsDecorated(node, parent, grandparent) {
14380         return node.decorators !== undefined
14381             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14382     }
14383     ts.nodeIsDecorated = nodeIsDecorated;
14384     function nodeOrChildIsDecorated(node, parent, grandparent) {
14385         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14386     }
14387     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14388     function childIsDecorated(node, parent) {
14389         switch (node.kind) {
14390             case 245 /* ClassDeclaration */:
14391                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14392             case 161 /* MethodDeclaration */:
14393             case 164 /* SetAccessor */:
14394                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14395             default:
14396                 return false;
14397         }
14398     }
14399     ts.childIsDecorated = childIsDecorated;
14400     function isJSXTagName(node) {
14401         var parent = node.parent;
14402         if (parent.kind === 268 /* JsxOpeningElement */ ||
14403             parent.kind === 267 /* JsxSelfClosingElement */ ||
14404             parent.kind === 269 /* JsxClosingElement */) {
14405             return parent.tagName === node;
14406         }
14407         return false;
14408     }
14409     ts.isJSXTagName = isJSXTagName;
14410     function isExpressionNode(node) {
14411         switch (node.kind) {
14412             case 102 /* SuperKeyword */:
14413             case 100 /* NullKeyword */:
14414             case 106 /* TrueKeyword */:
14415             case 91 /* FalseKeyword */:
14416             case 13 /* RegularExpressionLiteral */:
14417             case 192 /* ArrayLiteralExpression */:
14418             case 193 /* ObjectLiteralExpression */:
14419             case 194 /* PropertyAccessExpression */:
14420             case 195 /* ElementAccessExpression */:
14421             case 196 /* CallExpression */:
14422             case 197 /* NewExpression */:
14423             case 198 /* TaggedTemplateExpression */:
14424             case 217 /* AsExpression */:
14425             case 199 /* TypeAssertionExpression */:
14426             case 218 /* NonNullExpression */:
14427             case 200 /* ParenthesizedExpression */:
14428             case 201 /* FunctionExpression */:
14429             case 214 /* ClassExpression */:
14430             case 202 /* ArrowFunction */:
14431             case 205 /* VoidExpression */:
14432             case 203 /* DeleteExpression */:
14433             case 204 /* TypeOfExpression */:
14434             case 207 /* PrefixUnaryExpression */:
14435             case 208 /* PostfixUnaryExpression */:
14436             case 209 /* BinaryExpression */:
14437             case 210 /* ConditionalExpression */:
14438             case 213 /* SpreadElement */:
14439             case 211 /* TemplateExpression */:
14440             case 215 /* OmittedExpression */:
14441             case 266 /* JsxElement */:
14442             case 267 /* JsxSelfClosingElement */:
14443             case 270 /* JsxFragment */:
14444             case 212 /* YieldExpression */:
14445             case 206 /* AwaitExpression */:
14446             case 219 /* MetaProperty */:
14447                 return true;
14448             case 153 /* QualifiedName */:
14449                 while (node.parent.kind === 153 /* QualifiedName */) {
14450                     node = node.parent;
14451                 }
14452                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14453             case 75 /* Identifier */:
14454                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14455                     return true;
14456                 }
14457             // falls through
14458             case 8 /* NumericLiteral */:
14459             case 9 /* BigIntLiteral */:
14460             case 10 /* StringLiteral */:
14461             case 14 /* NoSubstitutionTemplateLiteral */:
14462             case 104 /* ThisKeyword */:
14463                 return isInExpressionContext(node);
14464             default:
14465                 return false;
14466         }
14467     }
14468     ts.isExpressionNode = isExpressionNode;
14469     function isInExpressionContext(node) {
14470         var parent = node.parent;
14471         switch (parent.kind) {
14472             case 242 /* VariableDeclaration */:
14473             case 156 /* Parameter */:
14474             case 159 /* PropertyDeclaration */:
14475             case 158 /* PropertySignature */:
14476             case 284 /* EnumMember */:
14477             case 281 /* PropertyAssignment */:
14478             case 191 /* BindingElement */:
14479                 return parent.initializer === node;
14480             case 226 /* ExpressionStatement */:
14481             case 227 /* IfStatement */:
14482             case 228 /* DoStatement */:
14483             case 229 /* WhileStatement */:
14484             case 235 /* ReturnStatement */:
14485             case 236 /* WithStatement */:
14486             case 237 /* SwitchStatement */:
14487             case 277 /* CaseClause */:
14488             case 239 /* ThrowStatement */:
14489                 return parent.expression === node;
14490             case 230 /* ForStatement */:
14491                 var forStatement = parent;
14492                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14493                     forStatement.condition === node ||
14494                     forStatement.incrementor === node;
14495             case 231 /* ForInStatement */:
14496             case 232 /* ForOfStatement */:
14497                 var forInStatement = parent;
14498                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14499                     forInStatement.expression === node;
14500             case 199 /* TypeAssertionExpression */:
14501             case 217 /* AsExpression */:
14502                 return node === parent.expression;
14503             case 221 /* TemplateSpan */:
14504                 return node === parent.expression;
14505             case 154 /* ComputedPropertyName */:
14506                 return node === parent.expression;
14507             case 157 /* Decorator */:
14508             case 276 /* JsxExpression */:
14509             case 275 /* JsxSpreadAttribute */:
14510             case 283 /* SpreadAssignment */:
14511                 return true;
14512             case 216 /* ExpressionWithTypeArguments */:
14513                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14514             case 282 /* ShorthandPropertyAssignment */:
14515                 return parent.objectAssignmentInitializer === node;
14516             default:
14517                 return isExpressionNode(parent);
14518         }
14519     }
14520     ts.isInExpressionContext = isInExpressionContext;
14521     function isPartOfTypeQuery(node) {
14522         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14523             node = node.parent;
14524         }
14525         return node.kind === 172 /* TypeQuery */;
14526     }
14527     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14528     function isExternalModuleImportEqualsDeclaration(node) {
14529         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14530     }
14531     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14532     function getExternalModuleImportEqualsDeclarationExpression(node) {
14533         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14534         return node.moduleReference.expression;
14535     }
14536     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14537     function isInternalModuleImportEqualsDeclaration(node) {
14538         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14539     }
14540     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14541     function isSourceFileJS(file) {
14542         return isInJSFile(file);
14543     }
14544     ts.isSourceFileJS = isSourceFileJS;
14545     function isSourceFileNotJS(file) {
14546         return !isInJSFile(file);
14547     }
14548     ts.isSourceFileNotJS = isSourceFileNotJS;
14549     function isInJSFile(node) {
14550         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14551     }
14552     ts.isInJSFile = isInJSFile;
14553     function isInJsonFile(node) {
14554         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14555     }
14556     ts.isInJsonFile = isInJsonFile;
14557     function isSourceFileNotJson(file) {
14558         return !isJsonSourceFile(file);
14559     }
14560     ts.isSourceFileNotJson = isSourceFileNotJson;
14561     function isInJSDoc(node) {
14562         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14563     }
14564     ts.isInJSDoc = isInJSDoc;
14565     function isJSDocIndexSignature(node) {
14566         return ts.isTypeReferenceNode(node) &&
14567             ts.isIdentifier(node.typeName) &&
14568             node.typeName.escapedText === "Object" &&
14569             node.typeArguments && node.typeArguments.length === 2 &&
14570             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14571     }
14572     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14573     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14574         if (callExpression.kind !== 196 /* CallExpression */) {
14575             return false;
14576         }
14577         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14578         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14579             return false;
14580         }
14581         if (args.length !== 1) {
14582             return false;
14583         }
14584         var arg = args[0];
14585         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14586     }
14587     ts.isRequireCall = isRequireCall;
14588     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14589         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14590     }
14591     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14592     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14593         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14594         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14595     }
14596     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14597     function isSingleOrDoubleQuote(charCode) {
14598         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14599     }
14600     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14601     function isStringDoubleQuoted(str, sourceFile) {
14602         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14603     }
14604     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14605     function getDeclarationOfExpando(node) {
14606         if (!node.parent) {
14607             return undefined;
14608         }
14609         var name;
14610         var decl;
14611         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14612             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14613                 return undefined;
14614             }
14615             name = node.parent.name;
14616             decl = node.parent;
14617         }
14618         else if (ts.isBinaryExpression(node.parent)) {
14619             var parentNode = node.parent;
14620             var parentNodeOperator = node.parent.operatorToken.kind;
14621             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14622                 name = parentNode.left;
14623                 decl = name;
14624             }
14625             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14626                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14627                     name = parentNode.parent.name;
14628                     decl = parentNode.parent;
14629                 }
14630                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14631                     name = parentNode.parent.left;
14632                     decl = name;
14633                 }
14634                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14635                     return undefined;
14636                 }
14637             }
14638         }
14639         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14640             return undefined;
14641         }
14642         return decl;
14643     }
14644     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14645     function isAssignmentDeclaration(decl) {
14646         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14647     }
14648     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14649     /** Get the initializer, taking into account defaulted Javascript initializers */
14650     function getEffectiveInitializer(node) {
14651         if (isInJSFile(node) && node.initializer &&
14652             ts.isBinaryExpression(node.initializer) &&
14653             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14654             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14655             return node.initializer.right;
14656         }
14657         return node.initializer;
14658     }
14659     ts.getEffectiveInitializer = getEffectiveInitializer;
14660     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14661     function getDeclaredExpandoInitializer(node) {
14662         var init = getEffectiveInitializer(node);
14663         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14664     }
14665     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14666     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14667         return ts.forEach(node.properties, function (p) {
14668             return ts.isPropertyAssignment(p) &&
14669                 ts.isIdentifier(p.name) &&
14670                 p.name.escapedText === "value" &&
14671                 p.initializer &&
14672                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14673         });
14674     }
14675     /**
14676      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14677      * We treat the right hand side of assignments with container-like initalizers as declarations.
14678      */
14679     function getAssignedExpandoInitializer(node) {
14680         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14681             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14682             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14683                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14684         }
14685         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14686             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14687             if (result) {
14688                 return result;
14689             }
14690         }
14691     }
14692     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14693     /**
14694      * Recognized expando initializers are:
14695      * 1. (function() {})() -- IIFEs
14696      * 2. function() { } -- Function expressions
14697      * 3. class { } -- Class expressions
14698      * 4. {} -- Empty object literals
14699      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14700      *
14701      * This function returns the provided initializer, or undefined if it is not valid.
14702      */
14703     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14704         if (ts.isCallExpression(initializer)) {
14705             var e = skipParentheses(initializer.expression);
14706             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14707         }
14708         if (initializer.kind === 201 /* FunctionExpression */ ||
14709             initializer.kind === 214 /* ClassExpression */ ||
14710             initializer.kind === 202 /* ArrowFunction */) {
14711             return initializer;
14712         }
14713         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14714             return initializer;
14715         }
14716     }
14717     ts.getExpandoInitializer = getExpandoInitializer;
14718     /**
14719      * A defaulted expando initializer matches the pattern
14720      * `Lhs = Lhs || ExpandoInitializer`
14721      * or `var Lhs = Lhs || ExpandoInitializer`
14722      *
14723      * The second Lhs is required to be the same as the first except that it may be prefixed with
14724      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14725      */
14726     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14727         var e = ts.isBinaryExpression(initializer)
14728             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14729             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14730         if (e && isSameEntityName(name, initializer.left)) {
14731             return e;
14732         }
14733     }
14734     function isDefaultedExpandoInitializer(node) {
14735         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14736             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14737                 undefined;
14738         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14739     }
14740     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14741     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14742     function getNameOfExpando(node) {
14743         if (ts.isBinaryExpression(node.parent)) {
14744             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14745             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14746                 return parent.left;
14747             }
14748         }
14749         else if (ts.isVariableDeclaration(node.parent)) {
14750             return node.parent.name;
14751         }
14752     }
14753     ts.getNameOfExpando = getNameOfExpando;
14754     /**
14755      * Is the 'declared' name the same as the one in the initializer?
14756      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14757      * 'window', 'self' or 'global'. For example:
14758      *
14759      * var my = my || {}
14760      * var min = window.min || {}
14761      * my.app = self.my.app || class { }
14762      */
14763     function isSameEntityName(name, initializer) {
14764         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14765             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14766         }
14767         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14768             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14769                 ts.isIdentifier(initializer.expression) &&
14770                     (initializer.expression.escapedText === "window" ||
14771                         initializer.expression.escapedText === "self" ||
14772                         initializer.expression.escapedText === "global"))) {
14773             var nameOrArgument = getNameOrArgument(initializer);
14774             if (ts.isPrivateIdentifier(nameOrArgument)) {
14775                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14776             }
14777             return isSameEntityName(name, nameOrArgument);
14778         }
14779         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14780             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14781                 && isSameEntityName(name.expression, initializer.expression);
14782         }
14783         return false;
14784     }
14785     function getRightMostAssignedExpression(node) {
14786         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14787             node = node.right;
14788         }
14789         return node;
14790     }
14791     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14792     function isExportsIdentifier(node) {
14793         return ts.isIdentifier(node) && node.escapedText === "exports";
14794     }
14795     ts.isExportsIdentifier = isExportsIdentifier;
14796     function isModuleIdentifier(node) {
14797         return ts.isIdentifier(node) && node.escapedText === "module";
14798     }
14799     ts.isModuleIdentifier = isModuleIdentifier;
14800     function isModuleExportsAccessExpression(node) {
14801         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14802             && isModuleIdentifier(node.expression)
14803             && getElementOrPropertyAccessName(node) === "exports";
14804     }
14805     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14806     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14807     /// assignments we treat as special in the binder
14808     function getAssignmentDeclarationKind(expr) {
14809         var special = getAssignmentDeclarationKindWorker(expr);
14810         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14811     }
14812     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14813     function isBindableObjectDefinePropertyCall(expr) {
14814         return ts.length(expr.arguments) === 3 &&
14815             ts.isPropertyAccessExpression(expr.expression) &&
14816             ts.isIdentifier(expr.expression.expression) &&
14817             ts.idText(expr.expression.expression) === "Object" &&
14818             ts.idText(expr.expression.name) === "defineProperty" &&
14819             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14820             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14821     }
14822     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14823     /** x.y OR x[0] */
14824     function isLiteralLikeAccess(node) {
14825         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14826     }
14827     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14828     /** x[0] OR x['a'] OR x[Symbol.y] */
14829     function isLiteralLikeElementAccess(node) {
14830         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14831             isWellKnownSymbolSyntactically(node.argumentExpression));
14832     }
14833     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14834     /** Any series of property and element accesses. */
14835     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14836         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14837             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14838     }
14839     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14840     /** Any series of property and element accesses, ending in a literal element access */
14841     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14842         return isLiteralLikeElementAccess(node)
14843             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
14844                 isEntityNameExpression(node.expression) ||
14845                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14846     }
14847     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14848     function isBindableStaticNameExpression(node, excludeThisKeyword) {
14849         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14850     }
14851     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14852     function getNameOrArgument(expr) {
14853         if (ts.isPropertyAccessExpression(expr)) {
14854             return expr.name;
14855         }
14856         return expr.argumentExpression;
14857     }
14858     ts.getNameOrArgument = getNameOrArgument;
14859     function getAssignmentDeclarationKindWorker(expr) {
14860         if (ts.isCallExpression(expr)) {
14861             if (!isBindableObjectDefinePropertyCall(expr)) {
14862                 return 0 /* None */;
14863             }
14864             var entityName = expr.arguments[0];
14865             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14866                 return 8 /* ObjectDefinePropertyExports */;
14867             }
14868             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14869                 return 9 /* ObjectDefinePrototypeProperty */;
14870             }
14871             return 7 /* ObjectDefinePropertyValue */;
14872         }
14873         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
14874             return 0 /* None */;
14875         }
14876         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14877             // F.prototype = { ... }
14878             return 6 /* Prototype */;
14879         }
14880         return getAssignmentDeclarationPropertyAccessKind(expr.left);
14881     }
14882     /**
14883      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14884      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14885      */
14886     /* @internal */
14887     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14888         if (ts.isPropertyAccessExpression(node)) {
14889             return node.name;
14890         }
14891         var arg = skipParentheses(node.argumentExpression);
14892         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14893             return arg;
14894         }
14895         return node;
14896     }
14897     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14898     function getElementOrPropertyAccessName(node) {
14899         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14900         if (name) {
14901             if (ts.isIdentifier(name)) {
14902                 return name.escapedText;
14903             }
14904             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14905                 return ts.escapeLeadingUnderscores(name.text);
14906             }
14907         }
14908         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14909             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14910         }
14911         return undefined;
14912     }
14913     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14914     function getAssignmentDeclarationPropertyAccessKind(lhs) {
14915         if (lhs.expression.kind === 104 /* ThisKeyword */) {
14916             return 4 /* ThisProperty */;
14917         }
14918         else if (isModuleExportsAccessExpression(lhs)) {
14919             // module.exports = expr
14920             return 2 /* ModuleExports */;
14921         }
14922         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14923             if (isPrototypeAccess(lhs.expression)) {
14924                 // F.G....prototype.x = expr
14925                 return 3 /* PrototypeProperty */;
14926             }
14927             var nextToLast = lhs;
14928             while (!ts.isIdentifier(nextToLast.expression)) {
14929                 nextToLast = nextToLast.expression;
14930             }
14931             var id = nextToLast.expression;
14932             if ((id.escapedText === "exports" ||
14933                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14934                 // ExportsProperty does not support binding with computed names
14935                 isBindableStaticAccessExpression(lhs)) {
14936                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14937                 return 1 /* ExportsProperty */;
14938             }
14939             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14940                 // F.G...x = expr
14941                 return 5 /* Property */;
14942             }
14943         }
14944         return 0 /* None */;
14945     }
14946     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14947     function getInitializerOfBinaryExpression(expr) {
14948         while (ts.isBinaryExpression(expr.right)) {
14949             expr = expr.right;
14950         }
14951         return expr.right;
14952     }
14953     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14954     function isPrototypePropertyAssignment(node) {
14955         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14956     }
14957     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14958     function isSpecialPropertyDeclaration(expr) {
14959         return isInJSFile(expr) &&
14960             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
14961             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14962             !!ts.getJSDocTypeTag(expr.parent);
14963     }
14964     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14965     function setValueDeclaration(symbol, node) {
14966         var valueDeclaration = symbol.valueDeclaration;
14967         if (!valueDeclaration ||
14968             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14969                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14970             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14971             // other kinds of value declarations take precedence over modules and assignment declarations
14972             symbol.valueDeclaration = node;
14973         }
14974     }
14975     ts.setValueDeclaration = setValueDeclaration;
14976     function isFunctionSymbol(symbol) {
14977         if (!symbol || !symbol.valueDeclaration) {
14978             return false;
14979         }
14980         var decl = symbol.valueDeclaration;
14981         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
14982     }
14983     ts.isFunctionSymbol = isFunctionSymbol;
14984     function importFromModuleSpecifier(node) {
14985         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
14986     }
14987     ts.importFromModuleSpecifier = importFromModuleSpecifier;
14988     function tryGetImportFromModuleSpecifier(node) {
14989         switch (node.parent.kind) {
14990             case 254 /* ImportDeclaration */:
14991             case 260 /* ExportDeclaration */:
14992                 return node.parent;
14993             case 265 /* ExternalModuleReference */:
14994                 return node.parent.parent;
14995             case 196 /* CallExpression */:
14996                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
14997             case 187 /* LiteralType */:
14998                 ts.Debug.assert(ts.isStringLiteral(node));
14999                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15000             default:
15001                 return undefined;
15002         }
15003     }
15004     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15005     function getExternalModuleName(node) {
15006         switch (node.kind) {
15007             case 254 /* ImportDeclaration */:
15008             case 260 /* ExportDeclaration */:
15009                 return node.moduleSpecifier;
15010             case 253 /* ImportEqualsDeclaration */:
15011                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15012             case 188 /* ImportType */:
15013                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15014             default:
15015                 return ts.Debug.assertNever(node);
15016         }
15017     }
15018     ts.getExternalModuleName = getExternalModuleName;
15019     function getNamespaceDeclarationNode(node) {
15020         switch (node.kind) {
15021             case 254 /* ImportDeclaration */:
15022                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15023             case 253 /* ImportEqualsDeclaration */:
15024                 return node;
15025             case 260 /* ExportDeclaration */:
15026                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15027             default:
15028                 return ts.Debug.assertNever(node);
15029         }
15030     }
15031     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15032     function isDefaultImport(node) {
15033         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15034     }
15035     ts.isDefaultImport = isDefaultImport;
15036     function forEachImportClauseDeclaration(node, action) {
15037         if (node.name) {
15038             var result = action(node);
15039             if (result)
15040                 return result;
15041         }
15042         if (node.namedBindings) {
15043             var result = ts.isNamespaceImport(node.namedBindings)
15044                 ? action(node.namedBindings)
15045                 : ts.forEach(node.namedBindings.elements, action);
15046             if (result)
15047                 return result;
15048         }
15049     }
15050     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15051     function hasQuestionToken(node) {
15052         if (node) {
15053             switch (node.kind) {
15054                 case 156 /* Parameter */:
15055                 case 161 /* MethodDeclaration */:
15056                 case 160 /* MethodSignature */:
15057                 case 282 /* ShorthandPropertyAssignment */:
15058                 case 281 /* PropertyAssignment */:
15059                 case 159 /* PropertyDeclaration */:
15060                 case 158 /* PropertySignature */:
15061                     return node.questionToken !== undefined;
15062             }
15063         }
15064         return false;
15065     }
15066     ts.hasQuestionToken = hasQuestionToken;
15067     function isJSDocConstructSignature(node) {
15068         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15069         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15070         return !!name && name.escapedText === "new";
15071     }
15072     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15073     function isJSDocTypeAlias(node) {
15074         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15075     }
15076     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15077     function isTypeAlias(node) {
15078         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15079     }
15080     ts.isTypeAlias = isTypeAlias;
15081     function getSourceOfAssignment(node) {
15082         return ts.isExpressionStatement(node) &&
15083             ts.isBinaryExpression(node.expression) &&
15084             node.expression.operatorToken.kind === 62 /* EqualsToken */
15085             ? getRightMostAssignedExpression(node.expression)
15086             : undefined;
15087     }
15088     function getSourceOfDefaultedAssignment(node) {
15089         return ts.isExpressionStatement(node) &&
15090             ts.isBinaryExpression(node.expression) &&
15091             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15092             ts.isBinaryExpression(node.expression.right) &&
15093             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15094             ? node.expression.right.right
15095             : undefined;
15096     }
15097     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15098         switch (node.kind) {
15099             case 225 /* VariableStatement */:
15100                 var v = getSingleVariableOfVariableStatement(node);
15101                 return v && v.initializer;
15102             case 159 /* PropertyDeclaration */:
15103                 return node.initializer;
15104             case 281 /* PropertyAssignment */:
15105                 return node.initializer;
15106         }
15107     }
15108     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15109     function getSingleVariableOfVariableStatement(node) {
15110         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15111     }
15112     function getNestedModuleDeclaration(node) {
15113         return ts.isModuleDeclaration(node) &&
15114             node.body &&
15115             node.body.kind === 249 /* ModuleDeclaration */
15116             ? node.body
15117             : undefined;
15118     }
15119     function getJSDocCommentsAndTags(hostNode) {
15120         var result;
15121         // Pull parameter comments from declaring function as well
15122         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15123             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15124         }
15125         var node = hostNode;
15126         while (node && node.parent) {
15127             if (ts.hasJSDocNodes(node)) {
15128                 result = ts.append(result, ts.last(node.jsDoc));
15129             }
15130             if (node.kind === 156 /* Parameter */) {
15131                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15132                 break;
15133             }
15134             if (node.kind === 155 /* TypeParameter */) {
15135                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15136                 break;
15137             }
15138             node = getNextJSDocCommentLocation(node);
15139         }
15140         return result || ts.emptyArray;
15141     }
15142     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15143     function getNextJSDocCommentLocation(node) {
15144         var parent = node.parent;
15145         if (parent.kind === 281 /* PropertyAssignment */ ||
15146             parent.kind === 259 /* ExportAssignment */ ||
15147             parent.kind === 159 /* PropertyDeclaration */ ||
15148             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15149             getNestedModuleDeclaration(parent) ||
15150             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15151             return parent;
15152         }
15153         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15154         // /**
15155         //   * @param {number} name
15156         //   * @returns {number}
15157         //   */
15158         // var x = function(name) { return name.length; }
15159         else if (parent.parent &&
15160             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15161                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15162             return parent.parent;
15163         }
15164         else if (parent.parent && parent.parent.parent &&
15165             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15166                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15167                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15168             return parent.parent.parent;
15169         }
15170     }
15171     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15172     function getParameterSymbolFromJSDoc(node) {
15173         if (node.symbol) {
15174             return node.symbol;
15175         }
15176         if (!ts.isIdentifier(node.name)) {
15177             return undefined;
15178         }
15179         var name = node.name.escapedText;
15180         var decl = getHostSignatureFromJSDoc(node);
15181         if (!decl) {
15182             return undefined;
15183         }
15184         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15185         return parameter && parameter.symbol;
15186     }
15187     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15188     function getHostSignatureFromJSDoc(node) {
15189         var host = getEffectiveJSDocHost(node);
15190         return host && ts.isFunctionLike(host) ? host : undefined;
15191     }
15192     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15193     function getEffectiveJSDocHost(node) {
15194         var host = getJSDocHost(node);
15195         var decl = getSourceOfDefaultedAssignment(host) ||
15196             getSourceOfAssignment(host) ||
15197             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15198             getSingleVariableOfVariableStatement(host) ||
15199             getNestedModuleDeclaration(host) ||
15200             host;
15201         return decl;
15202     }
15203     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15204     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15205     function getJSDocHost(node) {
15206         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15207     }
15208     ts.getJSDocHost = getJSDocHost;
15209     function getTypeParameterFromJsDoc(node) {
15210         var name = node.name.escapedText;
15211         var typeParameters = node.parent.parent.parent.typeParameters;
15212         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15213     }
15214     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15215     function hasRestParameter(s) {
15216         var last = ts.lastOrUndefined(s.parameters);
15217         return !!last && isRestParameter(last);
15218     }
15219     ts.hasRestParameter = hasRestParameter;
15220     function isRestParameter(node) {
15221         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15222         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15223     }
15224     ts.isRestParameter = isRestParameter;
15225     function hasTypeArguments(node) {
15226         return !!node.typeArguments;
15227     }
15228     ts.hasTypeArguments = hasTypeArguments;
15229     var AssignmentKind;
15230     (function (AssignmentKind) {
15231         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15232         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15233         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15234     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15235     function getAssignmentTargetKind(node) {
15236         var parent = node.parent;
15237         while (true) {
15238             switch (parent.kind) {
15239                 case 209 /* BinaryExpression */:
15240                     var binaryOperator = parent.operatorToken.kind;
15241                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15242                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15243                         0 /* None */;
15244                 case 207 /* PrefixUnaryExpression */:
15245                 case 208 /* PostfixUnaryExpression */:
15246                     var unaryOperator = parent.operator;
15247                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15248                 case 231 /* ForInStatement */:
15249                 case 232 /* ForOfStatement */:
15250                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15251                 case 200 /* ParenthesizedExpression */:
15252                 case 192 /* ArrayLiteralExpression */:
15253                 case 213 /* SpreadElement */:
15254                 case 218 /* NonNullExpression */:
15255                     node = parent;
15256                     break;
15257                 case 282 /* ShorthandPropertyAssignment */:
15258                     if (parent.name !== node) {
15259                         return 0 /* None */;
15260                     }
15261                     node = parent.parent;
15262                     break;
15263                 case 281 /* PropertyAssignment */:
15264                     if (parent.name === node) {
15265                         return 0 /* None */;
15266                     }
15267                     node = parent.parent;
15268                     break;
15269                 default:
15270                     return 0 /* None */;
15271             }
15272             parent = node.parent;
15273         }
15274     }
15275     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15276     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15277     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15278     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15279     // (Note that `p` is not a target in the above examples, only `a`.)
15280     function isAssignmentTarget(node) {
15281         return getAssignmentTargetKind(node) !== 0 /* None */;
15282     }
15283     ts.isAssignmentTarget = isAssignmentTarget;
15284     /**
15285      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15286      * the same `var` declaration scope as the node's parent.
15287      */
15288     function isNodeWithPossibleHoistedDeclaration(node) {
15289         switch (node.kind) {
15290             case 223 /* Block */:
15291             case 225 /* VariableStatement */:
15292             case 236 /* WithStatement */:
15293             case 227 /* IfStatement */:
15294             case 237 /* SwitchStatement */:
15295             case 251 /* CaseBlock */:
15296             case 277 /* CaseClause */:
15297             case 278 /* DefaultClause */:
15298             case 238 /* LabeledStatement */:
15299             case 230 /* ForStatement */:
15300             case 231 /* ForInStatement */:
15301             case 232 /* ForOfStatement */:
15302             case 228 /* DoStatement */:
15303             case 229 /* WhileStatement */:
15304             case 240 /* TryStatement */:
15305             case 280 /* CatchClause */:
15306                 return true;
15307         }
15308         return false;
15309     }
15310     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15311     function isValueSignatureDeclaration(node) {
15312         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15313     }
15314     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15315     function walkUp(node, kind) {
15316         while (node && node.kind === kind) {
15317             node = node.parent;
15318         }
15319         return node;
15320     }
15321     function walkUpParenthesizedTypes(node) {
15322         return walkUp(node, 182 /* ParenthesizedType */);
15323     }
15324     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15325     function walkUpParenthesizedExpressions(node) {
15326         return walkUp(node, 200 /* ParenthesizedExpression */);
15327     }
15328     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15329     function skipParentheses(node) {
15330         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15331     }
15332     ts.skipParentheses = skipParentheses;
15333     function skipParenthesesUp(node) {
15334         while (node.kind === 200 /* ParenthesizedExpression */) {
15335             node = node.parent;
15336         }
15337         return node;
15338     }
15339     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15340     function isDeleteTarget(node) {
15341         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15342             return false;
15343         }
15344         node = walkUpParenthesizedExpressions(node.parent);
15345         return node && node.kind === 203 /* DeleteExpression */;
15346     }
15347     ts.isDeleteTarget = isDeleteTarget;
15348     function isNodeDescendantOf(node, ancestor) {
15349         while (node) {
15350             if (node === ancestor)
15351                 return true;
15352             node = node.parent;
15353         }
15354         return false;
15355     }
15356     ts.isNodeDescendantOf = isNodeDescendantOf;
15357     // True if `name` is the name of a declaration node
15358     function isDeclarationName(name) {
15359         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15360     }
15361     ts.isDeclarationName = isDeclarationName;
15362     // See GH#16030
15363     function getDeclarationFromName(name) {
15364         var parent = name.parent;
15365         switch (name.kind) {
15366             case 10 /* StringLiteral */:
15367             case 14 /* NoSubstitutionTemplateLiteral */:
15368             case 8 /* NumericLiteral */:
15369                 if (ts.isComputedPropertyName(parent))
15370                     return parent.parent;
15371             // falls through
15372             case 75 /* Identifier */:
15373                 if (ts.isDeclaration(parent)) {
15374                     return parent.name === name ? parent : undefined;
15375                 }
15376                 else if (ts.isQualifiedName(parent)) {
15377                     var tag = parent.parent;
15378                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15379                 }
15380                 else {
15381                     var binExp = parent.parent;
15382                     return ts.isBinaryExpression(binExp) &&
15383                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15384                         (binExp.left.symbol || binExp.symbol) &&
15385                         ts.getNameOfDeclaration(binExp) === name
15386                         ? binExp
15387                         : undefined;
15388                 }
15389             case 76 /* PrivateIdentifier */:
15390                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15391             default:
15392                 return undefined;
15393         }
15394     }
15395     ts.getDeclarationFromName = getDeclarationFromName;
15396     function isLiteralComputedPropertyDeclarationName(node) {
15397         return isStringOrNumericLiteralLike(node) &&
15398             node.parent.kind === 154 /* ComputedPropertyName */ &&
15399             ts.isDeclaration(node.parent.parent);
15400     }
15401     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15402     // Return true if the given identifier is classified as an IdentifierName
15403     function isIdentifierName(node) {
15404         var parent = node.parent;
15405         switch (parent.kind) {
15406             case 159 /* PropertyDeclaration */:
15407             case 158 /* PropertySignature */:
15408             case 161 /* MethodDeclaration */:
15409             case 160 /* MethodSignature */:
15410             case 163 /* GetAccessor */:
15411             case 164 /* SetAccessor */:
15412             case 284 /* EnumMember */:
15413             case 281 /* PropertyAssignment */:
15414             case 194 /* PropertyAccessExpression */:
15415                 // Name in member declaration or property name in property access
15416                 return parent.name === node;
15417             case 153 /* QualifiedName */:
15418                 // Name on right hand side of dot in a type query or type reference
15419                 if (parent.right === node) {
15420                     while (parent.kind === 153 /* QualifiedName */) {
15421                         parent = parent.parent;
15422                     }
15423                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15424                 }
15425                 return false;
15426             case 191 /* BindingElement */:
15427             case 258 /* ImportSpecifier */:
15428                 // Property name in binding element or import specifier
15429                 return parent.propertyName === node;
15430             case 263 /* ExportSpecifier */:
15431             case 273 /* JsxAttribute */:
15432                 // Any name in an export specifier or JSX Attribute
15433                 return true;
15434         }
15435         return false;
15436     }
15437     ts.isIdentifierName = isIdentifierName;
15438     // An alias symbol is created by one of the following declarations:
15439     // import <symbol> = ...
15440     // import <symbol> from ...
15441     // import * as <symbol> from ...
15442     // import { x as <symbol> } from ...
15443     // export { x as <symbol> } from ...
15444     // export * as ns <symbol> from ...
15445     // export = <EntityNameExpression>
15446     // export default <EntityNameExpression>
15447     // module.exports = <EntityNameExpression>
15448     // {<Identifier>}
15449     // {name: <EntityNameExpression>}
15450     function isAliasSymbolDeclaration(node) {
15451         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15452             node.kind === 252 /* NamespaceExportDeclaration */ ||
15453             node.kind === 255 /* ImportClause */ && !!node.name ||
15454             node.kind === 256 /* NamespaceImport */ ||
15455             node.kind === 262 /* NamespaceExport */ ||
15456             node.kind === 258 /* ImportSpecifier */ ||
15457             node.kind === 263 /* ExportSpecifier */ ||
15458             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15459             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15460             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15461             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15462             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15463     }
15464     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15465     function getAliasDeclarationFromName(node) {
15466         switch (node.parent.kind) {
15467             case 255 /* ImportClause */:
15468             case 258 /* ImportSpecifier */:
15469             case 256 /* NamespaceImport */:
15470             case 263 /* ExportSpecifier */:
15471             case 259 /* ExportAssignment */:
15472             case 253 /* ImportEqualsDeclaration */:
15473                 return node.parent;
15474             case 153 /* QualifiedName */:
15475                 do {
15476                     node = node.parent;
15477                 } while (node.parent.kind === 153 /* QualifiedName */);
15478                 return getAliasDeclarationFromName(node);
15479         }
15480     }
15481     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15482     function isAliasableExpression(e) {
15483         return isEntityNameExpression(e) || ts.isClassExpression(e);
15484     }
15485     ts.isAliasableExpression = isAliasableExpression;
15486     function exportAssignmentIsAlias(node) {
15487         var e = getExportAssignmentExpression(node);
15488         return isAliasableExpression(e);
15489     }
15490     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15491     function getExportAssignmentExpression(node) {
15492         return ts.isExportAssignment(node) ? node.expression : node.right;
15493     }
15494     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15495     function getPropertyAssignmentAliasLikeExpression(node) {
15496         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15497             node.parent.right;
15498     }
15499     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15500     function getEffectiveBaseTypeNode(node) {
15501         var baseType = getClassExtendsHeritageElement(node);
15502         if (baseType && isInJSFile(node)) {
15503             // Prefer an @augments tag because it may have type parameters.
15504             var tag = ts.getJSDocAugmentsTag(node);
15505             if (tag) {
15506                 return tag.class;
15507             }
15508         }
15509         return baseType;
15510     }
15511     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15512     function getClassExtendsHeritageElement(node) {
15513         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15514         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15515     }
15516     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15517     function getEffectiveImplementsTypeNodes(node) {
15518         if (isInJSFile(node)) {
15519             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15520         }
15521         else {
15522             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15523             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15524         }
15525     }
15526     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15527     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15528     function getAllSuperTypeNodes(node) {
15529         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15530             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15531                 ts.emptyArray;
15532     }
15533     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15534     function getInterfaceBaseTypeNodes(node) {
15535         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15536         return heritageClause ? heritageClause.types : undefined;
15537     }
15538     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15539     function getHeritageClause(clauses, kind) {
15540         if (clauses) {
15541             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15542                 var clause = clauses_1[_i];
15543                 if (clause.token === kind) {
15544                     return clause;
15545                 }
15546             }
15547         }
15548         return undefined;
15549     }
15550     ts.getHeritageClause = getHeritageClause;
15551     function getAncestor(node, kind) {
15552         while (node) {
15553             if (node.kind === kind) {
15554                 return node;
15555             }
15556             node = node.parent;
15557         }
15558         return undefined;
15559     }
15560     ts.getAncestor = getAncestor;
15561     function isKeyword(token) {
15562         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15563     }
15564     ts.isKeyword = isKeyword;
15565     function isContextualKeyword(token) {
15566         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15567     }
15568     ts.isContextualKeyword = isContextualKeyword;
15569     function isNonContextualKeyword(token) {
15570         return isKeyword(token) && !isContextualKeyword(token);
15571     }
15572     ts.isNonContextualKeyword = isNonContextualKeyword;
15573     function isFutureReservedKeyword(token) {
15574         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15575     }
15576     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15577     function isStringANonContextualKeyword(name) {
15578         var token = ts.stringToToken(name);
15579         return token !== undefined && isNonContextualKeyword(token);
15580     }
15581     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15582     function isStringAKeyword(name) {
15583         var token = ts.stringToToken(name);
15584         return token !== undefined && isKeyword(token);
15585     }
15586     ts.isStringAKeyword = isStringAKeyword;
15587     function isIdentifierANonContextualKeyword(_a) {
15588         var originalKeywordKind = _a.originalKeywordKind;
15589         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15590     }
15591     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15592     function isTrivia(token) {
15593         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15594     }
15595     ts.isTrivia = isTrivia;
15596     var FunctionFlags;
15597     (function (FunctionFlags) {
15598         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15599         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15600         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15601         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15602         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15603     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15604     function getFunctionFlags(node) {
15605         if (!node) {
15606             return 4 /* Invalid */;
15607         }
15608         var flags = 0 /* Normal */;
15609         switch (node.kind) {
15610             case 244 /* FunctionDeclaration */:
15611             case 201 /* FunctionExpression */:
15612             case 161 /* MethodDeclaration */:
15613                 if (node.asteriskToken) {
15614                     flags |= 1 /* Generator */;
15615                 }
15616             // falls through
15617             case 202 /* ArrowFunction */:
15618                 if (hasModifier(node, 256 /* Async */)) {
15619                     flags |= 2 /* Async */;
15620                 }
15621                 break;
15622         }
15623         if (!node.body) {
15624             flags |= 4 /* Invalid */;
15625         }
15626         return flags;
15627     }
15628     ts.getFunctionFlags = getFunctionFlags;
15629     function isAsyncFunction(node) {
15630         switch (node.kind) {
15631             case 244 /* FunctionDeclaration */:
15632             case 201 /* FunctionExpression */:
15633             case 202 /* ArrowFunction */:
15634             case 161 /* MethodDeclaration */:
15635                 return node.body !== undefined
15636                     && node.asteriskToken === undefined
15637                     && hasModifier(node, 256 /* Async */);
15638         }
15639         return false;
15640     }
15641     ts.isAsyncFunction = isAsyncFunction;
15642     function isStringOrNumericLiteralLike(node) {
15643         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15644     }
15645     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15646     function isSignedNumericLiteral(node) {
15647         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15648     }
15649     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15650     /**
15651      * A declaration has a dynamic name if all of the following are true:
15652      *   1. The declaration has a computed property name.
15653      *   2. The computed name is *not* expressed as a StringLiteral.
15654      *   3. The computed name is *not* expressed as a NumericLiteral.
15655      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15656      *      immediately followed by a NumericLiteral.
15657      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15658      *      is a property of the Symbol constructor that denotes a built-in
15659      *      Symbol.
15660      */
15661     function hasDynamicName(declaration) {
15662         var name = ts.getNameOfDeclaration(declaration);
15663         return !!name && isDynamicName(name);
15664     }
15665     ts.hasDynamicName = hasDynamicName;
15666     function isDynamicName(name) {
15667         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15668             return false;
15669         }
15670         var expr = ts.isElementAccessExpression(name) ? name.argumentExpression : name.expression;
15671         return !isStringOrNumericLiteralLike(expr) &&
15672             !isSignedNumericLiteral(expr) &&
15673             !isWellKnownSymbolSyntactically(expr);
15674     }
15675     ts.isDynamicName = isDynamicName;
15676     /**
15677      * Checks if the expression is of the form:
15678      *    Symbol.name
15679      * where Symbol is literally the word "Symbol", and name is any identifierName
15680      */
15681     function isWellKnownSymbolSyntactically(node) {
15682         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15683     }
15684     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15685     function getPropertyNameForPropertyNameNode(name) {
15686         switch (name.kind) {
15687             case 75 /* Identifier */:
15688             case 76 /* PrivateIdentifier */:
15689                 return name.escapedText;
15690             case 10 /* StringLiteral */:
15691             case 8 /* NumericLiteral */:
15692                 return ts.escapeLeadingUnderscores(name.text);
15693             case 154 /* ComputedPropertyName */:
15694                 var nameExpression = name.expression;
15695                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15696                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15697                 }
15698                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15699                     return ts.escapeLeadingUnderscores(nameExpression.text);
15700                 }
15701                 return undefined;
15702             default:
15703                 return ts.Debug.assertNever(name);
15704         }
15705     }
15706     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15707     function isPropertyNameLiteral(node) {
15708         switch (node.kind) {
15709             case 75 /* Identifier */:
15710             case 10 /* StringLiteral */:
15711             case 14 /* NoSubstitutionTemplateLiteral */:
15712             case 8 /* NumericLiteral */:
15713                 return true;
15714             default:
15715                 return false;
15716         }
15717     }
15718     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15719     function getTextOfIdentifierOrLiteral(node) {
15720         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15721     }
15722     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15723     function getEscapedTextOfIdentifierOrLiteral(node) {
15724         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15725     }
15726     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15727     function getPropertyNameForUniqueESSymbol(symbol) {
15728         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15729     }
15730     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15731     function getPropertyNameForKnownSymbolName(symbolName) {
15732         return "__@" + symbolName;
15733     }
15734     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15735     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15736         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15737     }
15738     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15739     function isKnownSymbol(symbol) {
15740         return ts.startsWith(symbol.escapedName, "__@");
15741     }
15742     ts.isKnownSymbol = isKnownSymbol;
15743     /**
15744      * Includes the word "Symbol" with unicode escapes
15745      */
15746     function isESSymbolIdentifier(node) {
15747         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15748     }
15749     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15750     function isPushOrUnshiftIdentifier(node) {
15751         return node.escapedText === "push" || node.escapedText === "unshift";
15752     }
15753     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15754     function isParameterDeclaration(node) {
15755         var root = getRootDeclaration(node);
15756         return root.kind === 156 /* Parameter */;
15757     }
15758     ts.isParameterDeclaration = isParameterDeclaration;
15759     function getRootDeclaration(node) {
15760         while (node.kind === 191 /* BindingElement */) {
15761             node = node.parent.parent;
15762         }
15763         return node;
15764     }
15765     ts.getRootDeclaration = getRootDeclaration;
15766     function nodeStartsNewLexicalEnvironment(node) {
15767         var kind = node.kind;
15768         return kind === 162 /* Constructor */
15769             || kind === 201 /* FunctionExpression */
15770             || kind === 244 /* FunctionDeclaration */
15771             || kind === 202 /* ArrowFunction */
15772             || kind === 161 /* MethodDeclaration */
15773             || kind === 163 /* GetAccessor */
15774             || kind === 164 /* SetAccessor */
15775             || kind === 249 /* ModuleDeclaration */
15776             || kind === 290 /* SourceFile */;
15777     }
15778     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15779     function nodeIsSynthesized(range) {
15780         return positionIsSynthesized(range.pos)
15781             || positionIsSynthesized(range.end);
15782     }
15783     ts.nodeIsSynthesized = nodeIsSynthesized;
15784     function getOriginalSourceFile(sourceFile) {
15785         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15786     }
15787     ts.getOriginalSourceFile = getOriginalSourceFile;
15788     var Associativity;
15789     (function (Associativity) {
15790         Associativity[Associativity["Left"] = 0] = "Left";
15791         Associativity[Associativity["Right"] = 1] = "Right";
15792     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15793     function getExpressionAssociativity(expression) {
15794         var operator = getOperator(expression);
15795         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15796         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15797     }
15798     ts.getExpressionAssociativity = getExpressionAssociativity;
15799     function getOperatorAssociativity(kind, operator, hasArguments) {
15800         switch (kind) {
15801             case 197 /* NewExpression */:
15802                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15803             case 207 /* PrefixUnaryExpression */:
15804             case 204 /* TypeOfExpression */:
15805             case 205 /* VoidExpression */:
15806             case 203 /* DeleteExpression */:
15807             case 206 /* AwaitExpression */:
15808             case 210 /* ConditionalExpression */:
15809             case 212 /* YieldExpression */:
15810                 return 1 /* Right */;
15811             case 209 /* BinaryExpression */:
15812                 switch (operator) {
15813                     case 42 /* AsteriskAsteriskToken */:
15814                     case 62 /* EqualsToken */:
15815                     case 63 /* PlusEqualsToken */:
15816                     case 64 /* MinusEqualsToken */:
15817                     case 66 /* AsteriskAsteriskEqualsToken */:
15818                     case 65 /* AsteriskEqualsToken */:
15819                     case 67 /* SlashEqualsToken */:
15820                     case 68 /* PercentEqualsToken */:
15821                     case 69 /* LessThanLessThanEqualsToken */:
15822                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15823                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15824                     case 72 /* AmpersandEqualsToken */:
15825                     case 74 /* CaretEqualsToken */:
15826                     case 73 /* BarEqualsToken */:
15827                         return 1 /* Right */;
15828                 }
15829         }
15830         return 0 /* Left */;
15831     }
15832     ts.getOperatorAssociativity = getOperatorAssociativity;
15833     function getExpressionPrecedence(expression) {
15834         var operator = getOperator(expression);
15835         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15836         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15837     }
15838     ts.getExpressionPrecedence = getExpressionPrecedence;
15839     function getOperator(expression) {
15840         if (expression.kind === 209 /* BinaryExpression */) {
15841             return expression.operatorToken.kind;
15842         }
15843         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
15844             return expression.operator;
15845         }
15846         else {
15847             return expression.kind;
15848         }
15849     }
15850     ts.getOperator = getOperator;
15851     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15852         switch (nodeKind) {
15853             case 327 /* CommaListExpression */:
15854                 return 0;
15855             case 213 /* SpreadElement */:
15856                 return 1;
15857             case 212 /* YieldExpression */:
15858                 return 2;
15859             case 210 /* ConditionalExpression */:
15860                 return 4;
15861             case 209 /* BinaryExpression */:
15862                 switch (operatorKind) {
15863                     case 27 /* CommaToken */:
15864                         return 0;
15865                     case 62 /* EqualsToken */:
15866                     case 63 /* PlusEqualsToken */:
15867                     case 64 /* MinusEqualsToken */:
15868                     case 66 /* AsteriskAsteriskEqualsToken */:
15869                     case 65 /* AsteriskEqualsToken */:
15870                     case 67 /* SlashEqualsToken */:
15871                     case 68 /* PercentEqualsToken */:
15872                     case 69 /* LessThanLessThanEqualsToken */:
15873                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15874                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15875                     case 72 /* AmpersandEqualsToken */:
15876                     case 74 /* CaretEqualsToken */:
15877                     case 73 /* BarEqualsToken */:
15878                         return 3;
15879                     default:
15880                         return getBinaryOperatorPrecedence(operatorKind);
15881                 }
15882             case 207 /* PrefixUnaryExpression */:
15883             case 204 /* TypeOfExpression */:
15884             case 205 /* VoidExpression */:
15885             case 203 /* DeleteExpression */:
15886             case 206 /* AwaitExpression */:
15887                 return 16;
15888             case 208 /* PostfixUnaryExpression */:
15889                 return 17;
15890             case 196 /* CallExpression */:
15891                 return 18;
15892             case 197 /* NewExpression */:
15893                 return hasArguments ? 19 : 18;
15894             case 198 /* TaggedTemplateExpression */:
15895             case 194 /* PropertyAccessExpression */:
15896             case 195 /* ElementAccessExpression */:
15897                 return 19;
15898             case 104 /* ThisKeyword */:
15899             case 102 /* SuperKeyword */:
15900             case 75 /* Identifier */:
15901             case 100 /* NullKeyword */:
15902             case 106 /* TrueKeyword */:
15903             case 91 /* FalseKeyword */:
15904             case 8 /* NumericLiteral */:
15905             case 9 /* BigIntLiteral */:
15906             case 10 /* StringLiteral */:
15907             case 192 /* ArrayLiteralExpression */:
15908             case 193 /* ObjectLiteralExpression */:
15909             case 201 /* FunctionExpression */:
15910             case 202 /* ArrowFunction */:
15911             case 214 /* ClassExpression */:
15912             case 266 /* JsxElement */:
15913             case 267 /* JsxSelfClosingElement */:
15914             case 270 /* JsxFragment */:
15915             case 13 /* RegularExpressionLiteral */:
15916             case 14 /* NoSubstitutionTemplateLiteral */:
15917             case 211 /* TemplateExpression */:
15918             case 200 /* ParenthesizedExpression */:
15919             case 215 /* OmittedExpression */:
15920                 return 20;
15921             default:
15922                 return -1;
15923         }
15924     }
15925     ts.getOperatorPrecedence = getOperatorPrecedence;
15926     function getBinaryOperatorPrecedence(kind) {
15927         switch (kind) {
15928             case 60 /* QuestionQuestionToken */:
15929                 return 4;
15930             case 56 /* BarBarToken */:
15931                 return 5;
15932             case 55 /* AmpersandAmpersandToken */:
15933                 return 6;
15934             case 51 /* BarToken */:
15935                 return 7;
15936             case 52 /* CaretToken */:
15937                 return 8;
15938             case 50 /* AmpersandToken */:
15939                 return 9;
15940             case 34 /* EqualsEqualsToken */:
15941             case 35 /* ExclamationEqualsToken */:
15942             case 36 /* EqualsEqualsEqualsToken */:
15943             case 37 /* ExclamationEqualsEqualsToken */:
15944                 return 10;
15945             case 29 /* LessThanToken */:
15946             case 31 /* GreaterThanToken */:
15947             case 32 /* LessThanEqualsToken */:
15948             case 33 /* GreaterThanEqualsToken */:
15949             case 98 /* InstanceOfKeyword */:
15950             case 97 /* InKeyword */:
15951             case 123 /* AsKeyword */:
15952                 return 11;
15953             case 47 /* LessThanLessThanToken */:
15954             case 48 /* GreaterThanGreaterThanToken */:
15955             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15956                 return 12;
15957             case 39 /* PlusToken */:
15958             case 40 /* MinusToken */:
15959                 return 13;
15960             case 41 /* AsteriskToken */:
15961             case 43 /* SlashToken */:
15962             case 44 /* PercentToken */:
15963                 return 14;
15964             case 42 /* AsteriskAsteriskToken */:
15965                 return 15;
15966         }
15967         // -1 is lower than all other precedences.  Returning it will cause binary expression
15968         // parsing to stop.
15969         return -1;
15970     }
15971     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15972     function createDiagnosticCollection() {
15973         var nonFileDiagnostics = []; // See GH#19873
15974         var filesWithDiagnostics = [];
15975         var fileDiagnostics = ts.createMap();
15976         var hasReadNonFileDiagnostics = false;
15977         return {
15978             add: add,
15979             lookup: lookup,
15980             getGlobalDiagnostics: getGlobalDiagnostics,
15981             getDiagnostics: getDiagnostics,
15982             reattachFileDiagnostics: reattachFileDiagnostics
15983         };
15984         function reattachFileDiagnostics(newFile) {
15985             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
15986         }
15987         function lookup(diagnostic) {
15988             var diagnostics;
15989             if (diagnostic.file) {
15990                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
15991             }
15992             else {
15993                 diagnostics = nonFileDiagnostics;
15994             }
15995             if (!diagnostics) {
15996                 return undefined;
15997             }
15998             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
15999             if (result >= 0) {
16000                 return diagnostics[result];
16001             }
16002             return undefined;
16003         }
16004         function add(diagnostic) {
16005             var diagnostics;
16006             if (diagnostic.file) {
16007                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16008                 if (!diagnostics) {
16009                     diagnostics = []; // See GH#19873
16010                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16011                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16012                 }
16013             }
16014             else {
16015                 // If we've already read the non-file diagnostics, do not modify the existing array.
16016                 if (hasReadNonFileDiagnostics) {
16017                     hasReadNonFileDiagnostics = false;
16018                     nonFileDiagnostics = nonFileDiagnostics.slice();
16019                 }
16020                 diagnostics = nonFileDiagnostics;
16021             }
16022             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16023         }
16024         function getGlobalDiagnostics() {
16025             hasReadNonFileDiagnostics = true;
16026             return nonFileDiagnostics;
16027         }
16028         function getDiagnostics(fileName) {
16029             if (fileName) {
16030                 return fileDiagnostics.get(fileName) || [];
16031             }
16032             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16033             if (!nonFileDiagnostics.length) {
16034                 return fileDiags;
16035             }
16036             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16037             return fileDiags;
16038         }
16039     }
16040     ts.createDiagnosticCollection = createDiagnosticCollection;
16041     var templateSubstitutionRegExp = /\$\{/g;
16042     function escapeTemplateSubstitution(str) {
16043         return str.replace(templateSubstitutionRegExp, "\\${");
16044     }
16045     /** @internal */
16046     function hasInvalidEscape(template) {
16047         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16048             ? template.templateFlags
16049             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16050     }
16051     ts.hasInvalidEscape = hasInvalidEscape;
16052     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16053     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16054     // the language service. These characters should be escaped when printing, and if any characters are added,
16055     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16056     // There is no reason for this other than that JSON.stringify does not handle it either.
16057     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16058     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16059     // Template strings should be preserved as much as possible
16060     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16061     var escapedCharsMap = ts.createMapFromTemplate({
16062         "\t": "\\t",
16063         "\v": "\\v",
16064         "\f": "\\f",
16065         "\b": "\\b",
16066         "\r": "\\r",
16067         "\n": "\\n",
16068         "\\": "\\\\",
16069         "\"": "\\\"",
16070         "\'": "\\\'",
16071         "\`": "\\\`",
16072         "\u2028": "\\u2028",
16073         "\u2029": "\\u2029",
16074         "\u0085": "\\u0085" // nextLine
16075     });
16076     function encodeUtf16EscapeSequence(charCode) {
16077         var hexCharCode = charCode.toString(16).toUpperCase();
16078         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16079         return "\\u" + paddedHexCode;
16080     }
16081     function getReplacement(c, offset, input) {
16082         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16083             var lookAhead = input.charCodeAt(offset + c.length);
16084             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16085                 // 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)
16086                 return "\\x00";
16087             }
16088             // Otherwise, keep printing a literal \0 for the null character
16089             return "\\0";
16090         }
16091         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16092     }
16093     /**
16094      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16095      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16096      * Note that this doesn't actually wrap the input in double quotes.
16097      */
16098     function escapeString(s, quoteChar) {
16099         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16100             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16101                 doubleQuoteEscapedCharsRegExp;
16102         return s.replace(escapedCharsRegExp, getReplacement);
16103     }
16104     ts.escapeString = escapeString;
16105     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16106     function escapeNonAsciiString(s, quoteChar) {
16107         s = escapeString(s, quoteChar);
16108         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16109         // Otherwise just return the original string.
16110         return nonAsciiCharacters.test(s) ?
16111             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16112             s;
16113     }
16114     ts.escapeNonAsciiString = escapeNonAsciiString;
16115     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16116     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16117     // the language service. These characters should be escaped when printing, and if any characters are added,
16118     // the map below must be updated.
16119     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16120     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16121     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16122         "\"": "&quot;",
16123         "\'": "&apos;"
16124     });
16125     function encodeJsxCharacterEntity(charCode) {
16126         var hexCharCode = charCode.toString(16).toUpperCase();
16127         return "&#x" + hexCharCode + ";";
16128     }
16129     function getJsxAttributeStringReplacement(c) {
16130         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16131             return "&#0;";
16132         }
16133         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16134     }
16135     function escapeJsxAttributeString(s, quoteChar) {
16136         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16137             jsxDoubleQuoteEscapedCharsRegExp;
16138         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16139     }
16140     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16141     /**
16142      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16143      *
16144      * @return non-quoted string
16145      */
16146     function stripQuotes(name) {
16147         var length = name.length;
16148         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16149             return name.substring(1, length - 1);
16150         }
16151         return name;
16152     }
16153     ts.stripQuotes = stripQuotes;
16154     function isQuoteOrBacktick(charCode) {
16155         return charCode === 39 /* singleQuote */ ||
16156             charCode === 34 /* doubleQuote */ ||
16157             charCode === 96 /* backtick */;
16158     }
16159     function isIntrinsicJsxName(name) {
16160         var ch = name.charCodeAt(0);
16161         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16162     }
16163     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16164     var indentStrings = ["", "    "];
16165     function getIndentString(level) {
16166         if (indentStrings[level] === undefined) {
16167             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16168         }
16169         return indentStrings[level];
16170     }
16171     ts.getIndentString = getIndentString;
16172     function getIndentSize() {
16173         return indentStrings[1].length;
16174     }
16175     ts.getIndentSize = getIndentSize;
16176     function createTextWriter(newLine) {
16177         var output;
16178         var indent;
16179         var lineStart;
16180         var lineCount;
16181         var linePos;
16182         var hasTrailingComment = false;
16183         function updateLineCountAndPosFor(s) {
16184             var lineStartsOfS = ts.computeLineStarts(s);
16185             if (lineStartsOfS.length > 1) {
16186                 lineCount = lineCount + lineStartsOfS.length - 1;
16187                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16188                 lineStart = (linePos - output.length) === 0;
16189             }
16190             else {
16191                 lineStart = false;
16192             }
16193         }
16194         function writeText(s) {
16195             if (s && s.length) {
16196                 if (lineStart) {
16197                     s = getIndentString(indent) + s;
16198                     lineStart = false;
16199                 }
16200                 output += s;
16201                 updateLineCountAndPosFor(s);
16202             }
16203         }
16204         function write(s) {
16205             if (s)
16206                 hasTrailingComment = false;
16207             writeText(s);
16208         }
16209         function writeComment(s) {
16210             if (s)
16211                 hasTrailingComment = true;
16212             writeText(s);
16213         }
16214         function reset() {
16215             output = "";
16216             indent = 0;
16217             lineStart = true;
16218             lineCount = 0;
16219             linePos = 0;
16220             hasTrailingComment = false;
16221         }
16222         function rawWrite(s) {
16223             if (s !== undefined) {
16224                 output += s;
16225                 updateLineCountAndPosFor(s);
16226                 hasTrailingComment = false;
16227             }
16228         }
16229         function writeLiteral(s) {
16230             if (s && s.length) {
16231                 write(s);
16232             }
16233         }
16234         function writeLine(force) {
16235             if (!lineStart || force) {
16236                 output += newLine;
16237                 lineCount++;
16238                 linePos = output.length;
16239                 lineStart = true;
16240                 hasTrailingComment = false;
16241             }
16242         }
16243         function getTextPosWithWriteLine() {
16244             return lineStart ? output.length : (output.length + newLine.length);
16245         }
16246         reset();
16247         return {
16248             write: write,
16249             rawWrite: rawWrite,
16250             writeLiteral: writeLiteral,
16251             writeLine: writeLine,
16252             increaseIndent: function () { indent++; },
16253             decreaseIndent: function () { indent--; },
16254             getIndent: function () { return indent; },
16255             getTextPos: function () { return output.length; },
16256             getLine: function () { return lineCount; },
16257             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16258             getText: function () { return output; },
16259             isAtStartOfLine: function () { return lineStart; },
16260             hasTrailingComment: function () { return hasTrailingComment; },
16261             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16262             clear: reset,
16263             reportInaccessibleThisError: ts.noop,
16264             reportPrivateInBaseOfClassExpression: ts.noop,
16265             reportInaccessibleUniqueSymbolError: ts.noop,
16266             trackSymbol: ts.noop,
16267             writeKeyword: write,
16268             writeOperator: write,
16269             writeParameter: write,
16270             writeProperty: write,
16271             writePunctuation: write,
16272             writeSpace: write,
16273             writeStringLiteral: write,
16274             writeSymbol: function (s, _) { return write(s); },
16275             writeTrailingSemicolon: write,
16276             writeComment: writeComment,
16277             getTextPosWithWriteLine: getTextPosWithWriteLine
16278         };
16279     }
16280     ts.createTextWriter = createTextWriter;
16281     function getTrailingSemicolonDeferringWriter(writer) {
16282         var pendingTrailingSemicolon = false;
16283         function commitPendingTrailingSemicolon() {
16284             if (pendingTrailingSemicolon) {
16285                 writer.writeTrailingSemicolon(";");
16286                 pendingTrailingSemicolon = false;
16287             }
16288         }
16289         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16290                 pendingTrailingSemicolon = true;
16291             },
16292             writeLiteral: function (s) {
16293                 commitPendingTrailingSemicolon();
16294                 writer.writeLiteral(s);
16295             },
16296             writeStringLiteral: function (s) {
16297                 commitPendingTrailingSemicolon();
16298                 writer.writeStringLiteral(s);
16299             },
16300             writeSymbol: function (s, sym) {
16301                 commitPendingTrailingSemicolon();
16302                 writer.writeSymbol(s, sym);
16303             },
16304             writePunctuation: function (s) {
16305                 commitPendingTrailingSemicolon();
16306                 writer.writePunctuation(s);
16307             },
16308             writeKeyword: function (s) {
16309                 commitPendingTrailingSemicolon();
16310                 writer.writeKeyword(s);
16311             },
16312             writeOperator: function (s) {
16313                 commitPendingTrailingSemicolon();
16314                 writer.writeOperator(s);
16315             },
16316             writeParameter: function (s) {
16317                 commitPendingTrailingSemicolon();
16318                 writer.writeParameter(s);
16319             },
16320             writeSpace: function (s) {
16321                 commitPendingTrailingSemicolon();
16322                 writer.writeSpace(s);
16323             },
16324             writeProperty: function (s) {
16325                 commitPendingTrailingSemicolon();
16326                 writer.writeProperty(s);
16327             },
16328             writeComment: function (s) {
16329                 commitPendingTrailingSemicolon();
16330                 writer.writeComment(s);
16331             },
16332             writeLine: function () {
16333                 commitPendingTrailingSemicolon();
16334                 writer.writeLine();
16335             },
16336             increaseIndent: function () {
16337                 commitPendingTrailingSemicolon();
16338                 writer.increaseIndent();
16339             },
16340             decreaseIndent: function () {
16341                 commitPendingTrailingSemicolon();
16342                 writer.decreaseIndent();
16343             } });
16344     }
16345     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16346     function hostUsesCaseSensitiveFileNames(host) {
16347         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16348     }
16349     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16350     function hostGetCanonicalFileName(host) {
16351         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16352     }
16353     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16354     function getResolvedExternalModuleName(host, file, referenceFile) {
16355         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16356     }
16357     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16358     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16359         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16360         if (!file || file.isDeclarationFile) {
16361             return undefined;
16362         }
16363         return getResolvedExternalModuleName(host, file);
16364     }
16365     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16366     /**
16367      * Resolves a local path to a path which is absolute to the base of the emit
16368      */
16369     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16370         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16371         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16372         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16373         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16374         var extensionless = removeFileExtension(relativePath);
16375         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16376     }
16377     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16378     function getOwnEmitOutputFilePath(fileName, host, extension) {
16379         var compilerOptions = host.getCompilerOptions();
16380         var emitOutputFilePathWithoutExtension;
16381         if (compilerOptions.outDir) {
16382             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16383         }
16384         else {
16385             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16386         }
16387         return emitOutputFilePathWithoutExtension + extension;
16388     }
16389     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16390     function getDeclarationEmitOutputFilePath(fileName, host) {
16391         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16392     }
16393     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16394     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16395         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16396         var path = outputDir
16397             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16398             : fileName;
16399         return removeFileExtension(path) + ".d.ts" /* Dts */;
16400     }
16401     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16402     /**
16403      * Gets the source files that are expected to have an emit output.
16404      *
16405      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16406      * transformations.
16407      *
16408      * @param host An EmitHost.
16409      * @param targetSourceFile An optional target source file to emit.
16410      */
16411     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16412         var options = host.getCompilerOptions();
16413         if (options.outFile || options.out) {
16414             var moduleKind = getEmitModuleKind(options);
16415             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16416             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16417             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16418                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16419                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16420             });
16421         }
16422         else {
16423             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16424             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16425         }
16426     }
16427     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16428     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16429     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16430         var options = host.getCompilerOptions();
16431         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16432             !sourceFile.isDeclarationFile &&
16433             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16434             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16435             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16436     }
16437     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16438     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16439         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16440     }
16441     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16442     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16443         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16444         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16445         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16446         return ts.combinePaths(newDirPath, sourceFilePath);
16447     }
16448     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16449     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16450         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16451             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16452         }, sourceFiles);
16453     }
16454     ts.writeFile = writeFile;
16455     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16456         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16457             var parentDirectory = ts.getDirectoryPath(directoryPath);
16458             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16459             createDirectory(directoryPath);
16460         }
16461     }
16462     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16463         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16464         // and fall back to creating it if the file write fails.
16465         try {
16466             writeFile(path, data, writeByteOrderMark);
16467         }
16468         catch (_a) {
16469             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16470             writeFile(path, data, writeByteOrderMark);
16471         }
16472     }
16473     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16474     function getLineOfLocalPosition(sourceFile, pos) {
16475         var lineStarts = ts.getLineStarts(sourceFile);
16476         return ts.computeLineOfPosition(lineStarts, pos);
16477     }
16478     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16479     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16480         return ts.computeLineOfPosition(lineMap, pos);
16481     }
16482     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16483     function getFirstConstructorWithBody(node) {
16484         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16485     }
16486     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16487     function getSetAccessorValueParameter(accessor) {
16488         if (accessor && accessor.parameters.length > 0) {
16489             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16490             return accessor.parameters[hasThis ? 1 : 0];
16491         }
16492     }
16493     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16494     /** Get the type annotation for the value parameter. */
16495     function getSetAccessorTypeAnnotationNode(accessor) {
16496         var parameter = getSetAccessorValueParameter(accessor);
16497         return parameter && parameter.type;
16498     }
16499     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16500     function getThisParameter(signature) {
16501         // callback tags do not currently support this parameters
16502         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16503             var thisParameter = signature.parameters[0];
16504             if (parameterIsThisKeyword(thisParameter)) {
16505                 return thisParameter;
16506             }
16507         }
16508     }
16509     ts.getThisParameter = getThisParameter;
16510     function parameterIsThisKeyword(parameter) {
16511         return isThisIdentifier(parameter.name);
16512     }
16513     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16514     function isThisIdentifier(node) {
16515         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16516     }
16517     ts.isThisIdentifier = isThisIdentifier;
16518     function identifierIsThisKeyword(id) {
16519         return id.originalKeywordKind === 104 /* ThisKeyword */;
16520     }
16521     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16522     function getAllAccessorDeclarations(declarations, accessor) {
16523         // TODO: GH#18217
16524         var firstAccessor;
16525         var secondAccessor;
16526         var getAccessor;
16527         var setAccessor;
16528         if (hasDynamicName(accessor)) {
16529             firstAccessor = accessor;
16530             if (accessor.kind === 163 /* GetAccessor */) {
16531                 getAccessor = accessor;
16532             }
16533             else if (accessor.kind === 164 /* SetAccessor */) {
16534                 setAccessor = accessor;
16535             }
16536             else {
16537                 ts.Debug.fail("Accessor has wrong kind");
16538             }
16539         }
16540         else {
16541             ts.forEach(declarations, function (member) {
16542                 if (ts.isAccessor(member)
16543                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16544                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16545                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16546                     if (memberName === accessorName) {
16547                         if (!firstAccessor) {
16548                             firstAccessor = member;
16549                         }
16550                         else if (!secondAccessor) {
16551                             secondAccessor = member;
16552                         }
16553                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16554                             // eslint-disable-next-line
16555                             getAccessor = member;
16556                         }
16557                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16558                             // eslint-disable-next-line
16559                             setAccessor = member;
16560                         }
16561                     }
16562                 }
16563             });
16564         }
16565         return {
16566             firstAccessor: firstAccessor,
16567             secondAccessor: secondAccessor,
16568             getAccessor: getAccessor,
16569             setAccessor: setAccessor
16570         };
16571     }
16572     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16573     /**
16574      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16575      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16576      * functions only the JSDoc case.
16577      */
16578     function getEffectiveTypeAnnotationNode(node) {
16579         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16580             return undefined;
16581         var type = node.type;
16582         if (type || !isInJSFile(node))
16583             return type;
16584         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16585     }
16586     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16587     function getTypeAnnotationNode(node) {
16588         return node.type;
16589     }
16590     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16591     /**
16592      * Gets the effective return type annotation of a signature. If the node was parsed in a
16593      * JavaScript file, gets the return type annotation from JSDoc.
16594      */
16595     function getEffectiveReturnTypeNode(node) {
16596         return ts.isJSDocSignature(node) ?
16597             node.type && node.type.typeExpression && node.type.typeExpression.type :
16598             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16599     }
16600     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16601     function getJSDocTypeParameterDeclarations(node) {
16602         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16603     }
16604     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16605     /** template tags are only available when a typedef isn't already using them */
16606     function isNonTypeAliasTemplate(tag) {
16607         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16608     }
16609     /**
16610      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16611      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16612      */
16613     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16614         var parameter = getSetAccessorValueParameter(node);
16615         return parameter && getEffectiveTypeAnnotationNode(parameter);
16616     }
16617     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16618     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16619         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16620     }
16621     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16622     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16623         // If the leading comments start on different line than the start of node, write new line
16624         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16625             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16626             writer.writeLine();
16627         }
16628     }
16629     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16630     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16631         // If the leading comments start on different line than the start of node, write new line
16632         if (pos !== commentPos &&
16633             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16634             writer.writeLine();
16635         }
16636     }
16637     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16638     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16639         if (comments && comments.length > 0) {
16640             if (leadingSeparator) {
16641                 writer.writeSpace(" ");
16642             }
16643             var emitInterveningSeparator = false;
16644             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16645                 var comment = comments_1[_i];
16646                 if (emitInterveningSeparator) {
16647                     writer.writeSpace(" ");
16648                     emitInterveningSeparator = false;
16649                 }
16650                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16651                 if (comment.hasTrailingNewLine) {
16652                     writer.writeLine();
16653                 }
16654                 else {
16655                     emitInterveningSeparator = true;
16656                 }
16657             }
16658             if (emitInterveningSeparator && trailingSeparator) {
16659                 writer.writeSpace(" ");
16660             }
16661         }
16662     }
16663     ts.emitComments = emitComments;
16664     /**
16665      * Detached comment is a comment at the top of file or function body that is separated from
16666      * the next statement by space.
16667      */
16668     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16669         var leadingComments;
16670         var currentDetachedCommentInfo;
16671         if (removeComments) {
16672             // removeComments is true, only reserve pinned comment at the top of file
16673             // For example:
16674             //      /*! Pinned Comment */
16675             //
16676             //      var x = 10;
16677             if (node.pos === 0) {
16678                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16679             }
16680         }
16681         else {
16682             // removeComments is false, just get detached as normal and bypass the process to filter comment
16683             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16684         }
16685         if (leadingComments) {
16686             var detachedComments = [];
16687             var lastComment = void 0;
16688             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16689                 var comment = leadingComments_1[_i];
16690                 if (lastComment) {
16691                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16692                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16693                     if (commentLine >= lastCommentLine + 2) {
16694                         // There was a blank line between the last comment and this comment.  This
16695                         // comment is not part of the copyright comments.  Return what we have so
16696                         // far.
16697                         break;
16698                     }
16699                 }
16700                 detachedComments.push(comment);
16701                 lastComment = comment;
16702             }
16703             if (detachedComments.length) {
16704                 // All comments look like they could have been part of the copyright header.  Make
16705                 // sure there is at least one blank line between it and the node.  If not, it's not
16706                 // a copyright header.
16707                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16708                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16709                 if (nodeLine >= lastCommentLine + 2) {
16710                     // Valid detachedComments
16711                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16712                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16713                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16714                 }
16715             }
16716         }
16717         return currentDetachedCommentInfo;
16718         function isPinnedCommentLocal(comment) {
16719             return isPinnedComment(text, comment.pos);
16720         }
16721     }
16722     ts.emitDetachedComments = emitDetachedComments;
16723     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16724         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16725             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16726             var lineCount = lineMap.length;
16727             var firstCommentLineIndent = void 0;
16728             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16729                 var nextLineStart = (currentLine + 1) === lineCount
16730                     ? text.length + 1
16731                     : lineMap[currentLine + 1];
16732                 if (pos !== commentPos) {
16733                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16734                     if (firstCommentLineIndent === undefined) {
16735                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16736                     }
16737                     // These are number of spaces writer is going to write at current indent
16738                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16739                     // Number of spaces we want to be writing
16740                     // eg: Assume writer indent
16741                     // module m {
16742                     //         /* starts at character 9 this is line 1
16743                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16744                     //   More left indented comment */                            --2  = 8 - 8 + 2
16745                     //     class c { }
16746                     // }
16747                     // module m {
16748                     //     /* this is line 1 -- Assume current writer indent 8
16749                     //      * line                                                --3 = 8 - 4 + 5
16750                     //            More right indented comment */                  --4 = 8 - 4 + 11
16751                     //     class c { }
16752                     // }
16753                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16754                     if (spacesToEmit > 0) {
16755                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16756                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16757                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16758                         writer.rawWrite(indentSizeSpaceString);
16759                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16760                         while (numberOfSingleSpacesToEmit) {
16761                             writer.rawWrite(" ");
16762                             numberOfSingleSpacesToEmit--;
16763                         }
16764                     }
16765                     else {
16766                         // No spaces to emit write empty string
16767                         writer.rawWrite("");
16768                     }
16769                 }
16770                 // Write the comment line text
16771                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16772                 pos = nextLineStart;
16773             }
16774         }
16775         else {
16776             // Single line comment of style //....
16777             writer.writeComment(text.substring(commentPos, commentEnd));
16778         }
16779     }
16780     ts.writeCommentRange = writeCommentRange;
16781     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16782         var end = Math.min(commentEnd, nextLineStart - 1);
16783         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16784         if (currentLineText) {
16785             // trimmed forward and ending spaces text
16786             writer.writeComment(currentLineText);
16787             if (end !== commentEnd) {
16788                 writer.writeLine();
16789             }
16790         }
16791         else {
16792             // Empty string - make sure we write empty line
16793             writer.rawWrite(newLine);
16794         }
16795     }
16796     function calculateIndent(text, pos, end) {
16797         var currentLineIndent = 0;
16798         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16799             if (text.charCodeAt(pos) === 9 /* tab */) {
16800                 // Tabs = TabSize = indent size and go to next tabStop
16801                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16802             }
16803             else {
16804                 // Single space
16805                 currentLineIndent++;
16806             }
16807         }
16808         return currentLineIndent;
16809     }
16810     function hasModifiers(node) {
16811         return getModifierFlags(node) !== 0 /* None */;
16812     }
16813     ts.hasModifiers = hasModifiers;
16814     function hasModifier(node, flags) {
16815         return !!getSelectedModifierFlags(node, flags);
16816     }
16817     ts.hasModifier = hasModifier;
16818     function hasStaticModifier(node) {
16819         return hasModifier(node, 32 /* Static */);
16820     }
16821     ts.hasStaticModifier = hasStaticModifier;
16822     function hasReadonlyModifier(node) {
16823         return hasModifier(node, 64 /* Readonly */);
16824     }
16825     ts.hasReadonlyModifier = hasReadonlyModifier;
16826     function getSelectedModifierFlags(node, flags) {
16827         return getModifierFlags(node) & flags;
16828     }
16829     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16830     function getModifierFlags(node) {
16831         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16832             return 0 /* None */;
16833         }
16834         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16835             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16836         }
16837         var flags = getModifierFlagsNoCache(node);
16838         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
16839         return flags;
16840     }
16841     ts.getModifierFlags = getModifierFlags;
16842     function getModifierFlagsNoCache(node) {
16843         var flags = 0 /* None */;
16844         if (node.modifiers) {
16845             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
16846                 var modifier = _a[_i];
16847                 flags |= modifierToFlag(modifier.kind);
16848             }
16849         }
16850         if (isInJSFile(node) && !!node.parent) {
16851             // getModifierFlagsNoCache should only be called when parent pointers are set,
16852             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
16853             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
16854                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
16855                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
16856                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
16857             flags |= tags;
16858         }
16859         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
16860             flags |= 1 /* Export */;
16861         }
16862         return flags;
16863     }
16864     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
16865     function modifierToFlag(token) {
16866         switch (token) {
16867             case 120 /* StaticKeyword */: return 32 /* Static */;
16868             case 119 /* PublicKeyword */: return 4 /* Public */;
16869             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
16870             case 117 /* PrivateKeyword */: return 8 /* Private */;
16871             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
16872             case 89 /* ExportKeyword */: return 1 /* Export */;
16873             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
16874             case 81 /* ConstKeyword */: return 2048 /* Const */;
16875             case 84 /* DefaultKeyword */: return 512 /* Default */;
16876             case 126 /* AsyncKeyword */: return 256 /* Async */;
16877             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
16878         }
16879         return 0 /* None */;
16880     }
16881     ts.modifierToFlag = modifierToFlag;
16882     function isLogicalOperator(token) {
16883         return token === 56 /* BarBarToken */
16884             || token === 55 /* AmpersandAmpersandToken */
16885             || token === 53 /* ExclamationToken */;
16886     }
16887     ts.isLogicalOperator = isLogicalOperator;
16888     function isAssignmentOperator(token) {
16889         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
16890     }
16891     ts.isAssignmentOperator = isAssignmentOperator;
16892     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16893     function tryGetClassExtendingExpressionWithTypeArguments(node) {
16894         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16895         return cls && !cls.isImplements ? cls.class : undefined;
16896     }
16897     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16898     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16899         return ts.isExpressionWithTypeArguments(node)
16900             && ts.isHeritageClause(node.parent)
16901             && ts.isClassLike(node.parent.parent)
16902             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
16903             : undefined;
16904     }
16905     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16906     function isAssignmentExpression(node, excludeCompoundAssignment) {
16907         return ts.isBinaryExpression(node)
16908             && (excludeCompoundAssignment
16909                 ? node.operatorToken.kind === 62 /* EqualsToken */
16910                 : isAssignmentOperator(node.operatorToken.kind))
16911             && ts.isLeftHandSideExpression(node.left);
16912     }
16913     ts.isAssignmentExpression = isAssignmentExpression;
16914     function isDestructuringAssignment(node) {
16915         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16916             var kind = node.left.kind;
16917             return kind === 193 /* ObjectLiteralExpression */
16918                 || kind === 192 /* ArrayLiteralExpression */;
16919         }
16920         return false;
16921     }
16922     ts.isDestructuringAssignment = isDestructuringAssignment;
16923     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16924         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16925     }
16926     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16927     function isEntityNameExpression(node) {
16928         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16929     }
16930     ts.isEntityNameExpression = isEntityNameExpression;
16931     function getFirstIdentifier(node) {
16932         switch (node.kind) {
16933             case 75 /* Identifier */:
16934                 return node;
16935             case 153 /* QualifiedName */:
16936                 do {
16937                     node = node.left;
16938                 } while (node.kind !== 75 /* Identifier */);
16939                 return node;
16940             case 194 /* PropertyAccessExpression */:
16941                 do {
16942                     node = node.expression;
16943                 } while (node.kind !== 75 /* Identifier */);
16944                 return node;
16945         }
16946     }
16947     ts.getFirstIdentifier = getFirstIdentifier;
16948     function isDottedName(node) {
16949         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
16950             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16951             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
16952     }
16953     ts.isDottedName = isDottedName;
16954     function isPropertyAccessEntityNameExpression(node) {
16955         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16956     }
16957     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16958     function tryGetPropertyAccessOrIdentifierToString(expr) {
16959         if (ts.isPropertyAccessExpression(expr)) {
16960             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16961             if (baseStr !== undefined) {
16962                 return baseStr + "." + expr.name;
16963             }
16964         }
16965         else if (ts.isIdentifier(expr)) {
16966             return ts.unescapeLeadingUnderscores(expr.escapedText);
16967         }
16968         return undefined;
16969     }
16970     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16971     function isPrototypeAccess(node) {
16972         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16973     }
16974     ts.isPrototypeAccess = isPrototypeAccess;
16975     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16976         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
16977             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
16978     }
16979     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
16980     function isEmptyObjectLiteral(expression) {
16981         return expression.kind === 193 /* ObjectLiteralExpression */ &&
16982             expression.properties.length === 0;
16983     }
16984     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
16985     function isEmptyArrayLiteral(expression) {
16986         return expression.kind === 192 /* ArrayLiteralExpression */ &&
16987             expression.elements.length === 0;
16988     }
16989     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
16990     function getLocalSymbolForExportDefault(symbol) {
16991         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
16992     }
16993     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
16994     function isExportDefaultSymbol(symbol) {
16995         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
16996     }
16997     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
16998     function tryExtractTSExtension(fileName) {
16999         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17000     }
17001     ts.tryExtractTSExtension = tryExtractTSExtension;
17002     /**
17003      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17004      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17005      */
17006     function getExpandedCharCodes(input) {
17007         var output = [];
17008         var length = input.length;
17009         for (var i = 0; i < length; i++) {
17010             var charCode = input.charCodeAt(i);
17011             // handle utf8
17012             if (charCode < 0x80) {
17013                 output.push(charCode);
17014             }
17015             else if (charCode < 0x800) {
17016                 output.push((charCode >> 6) | 192);
17017                 output.push((charCode & 63) | 128);
17018             }
17019             else if (charCode < 0x10000) {
17020                 output.push((charCode >> 12) | 224);
17021                 output.push(((charCode >> 6) & 63) | 128);
17022                 output.push((charCode & 63) | 128);
17023             }
17024             else if (charCode < 0x20000) {
17025                 output.push((charCode >> 18) | 240);
17026                 output.push(((charCode >> 12) & 63) | 128);
17027                 output.push(((charCode >> 6) & 63) | 128);
17028                 output.push((charCode & 63) | 128);
17029             }
17030             else {
17031                 ts.Debug.assert(false, "Unexpected code point");
17032             }
17033         }
17034         return output;
17035     }
17036     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17037     /**
17038      * Converts a string to a base-64 encoded ASCII string.
17039      */
17040     function convertToBase64(input) {
17041         var result = "";
17042         var charCodes = getExpandedCharCodes(input);
17043         var i = 0;
17044         var length = charCodes.length;
17045         var byte1, byte2, byte3, byte4;
17046         while (i < length) {
17047             // Convert every 6-bits in the input 3 character points
17048             // into a base64 digit
17049             byte1 = charCodes[i] >> 2;
17050             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17051             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17052             byte4 = charCodes[i + 2] & 63;
17053             // We are out of characters in the input, set the extra
17054             // digits to 64 (padding character).
17055             if (i + 1 >= length) {
17056                 byte3 = byte4 = 64;
17057             }
17058             else if (i + 2 >= length) {
17059                 byte4 = 64;
17060             }
17061             // Write to the output
17062             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17063             i += 3;
17064         }
17065         return result;
17066     }
17067     ts.convertToBase64 = convertToBase64;
17068     function getStringFromExpandedCharCodes(codes) {
17069         var output = "";
17070         var i = 0;
17071         var length = codes.length;
17072         while (i < length) {
17073             var charCode = codes[i];
17074             if (charCode < 0x80) {
17075                 output += String.fromCharCode(charCode);
17076                 i++;
17077             }
17078             else if ((charCode & 192) === 192) {
17079                 var value = charCode & 63;
17080                 i++;
17081                 var nextCode = codes[i];
17082                 while ((nextCode & 192) === 128) {
17083                     value = (value << 6) | (nextCode & 63);
17084                     i++;
17085                     nextCode = codes[i];
17086                 }
17087                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17088                 output += String.fromCharCode(value);
17089             }
17090             else {
17091                 // We don't want to kill the process when decoding fails (due to a following char byte not
17092                 // following a leading char), so we just print the (bad) value
17093                 output += String.fromCharCode(charCode);
17094                 i++;
17095             }
17096         }
17097         return output;
17098     }
17099     function base64encode(host, input) {
17100         if (host && host.base64encode) {
17101             return host.base64encode(input);
17102         }
17103         return convertToBase64(input);
17104     }
17105     ts.base64encode = base64encode;
17106     function base64decode(host, input) {
17107         if (host && host.base64decode) {
17108             return host.base64decode(input);
17109         }
17110         var length = input.length;
17111         var expandedCharCodes = [];
17112         var i = 0;
17113         while (i < length) {
17114             // Stop decoding once padding characters are present
17115             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17116                 break;
17117             }
17118             // convert 4 input digits into three characters, ignoring padding characters at the end
17119             var ch1 = base64Digits.indexOf(input[i]);
17120             var ch2 = base64Digits.indexOf(input[i + 1]);
17121             var ch3 = base64Digits.indexOf(input[i + 2]);
17122             var ch4 = base64Digits.indexOf(input[i + 3]);
17123             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17124             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17125             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17126             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17127                 expandedCharCodes.push(code1);
17128             }
17129             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17130                 expandedCharCodes.push(code1, code2);
17131             }
17132             else {
17133                 expandedCharCodes.push(code1, code2, code3);
17134             }
17135             i += 4;
17136         }
17137         return getStringFromExpandedCharCodes(expandedCharCodes);
17138     }
17139     ts.base64decode = base64decode;
17140     function readJson(path, host) {
17141         try {
17142             var jsonText = host.readFile(path);
17143             if (!jsonText)
17144                 return {};
17145             var result = ts.parseConfigFileTextToJson(path, jsonText);
17146             if (result.error) {
17147                 return {};
17148             }
17149             return result.config;
17150         }
17151         catch (e) {
17152             // gracefully handle if readFile fails or returns not JSON
17153             return {};
17154         }
17155     }
17156     ts.readJson = readJson;
17157     function directoryProbablyExists(directoryName, host) {
17158         // if host does not support 'directoryExists' assume that directory will exist
17159         return !host.directoryExists || host.directoryExists(directoryName);
17160     }
17161     ts.directoryProbablyExists = directoryProbablyExists;
17162     var carriageReturnLineFeed = "\r\n";
17163     var lineFeed = "\n";
17164     function getNewLineCharacter(options, getNewLine) {
17165         switch (options.newLine) {
17166             case 0 /* CarriageReturnLineFeed */:
17167                 return carriageReturnLineFeed;
17168             case 1 /* LineFeed */:
17169                 return lineFeed;
17170         }
17171         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17172     }
17173     ts.getNewLineCharacter = getNewLineCharacter;
17174     /**
17175      * Creates a new TextRange from the provided pos and end.
17176      *
17177      * @param pos The start position.
17178      * @param end The end position.
17179      */
17180     function createRange(pos, end) {
17181         if (end === void 0) { end = pos; }
17182         ts.Debug.assert(end >= pos || end === -1);
17183         return { pos: pos, end: end };
17184     }
17185     ts.createRange = createRange;
17186     /**
17187      * Creates a new TextRange from a provided range with a new end position.
17188      *
17189      * @param range A TextRange.
17190      * @param end The new end position.
17191      */
17192     function moveRangeEnd(range, end) {
17193         return createRange(range.pos, end);
17194     }
17195     ts.moveRangeEnd = moveRangeEnd;
17196     /**
17197      * Creates a new TextRange from a provided range with a new start position.
17198      *
17199      * @param range A TextRange.
17200      * @param pos The new Start position.
17201      */
17202     function moveRangePos(range, pos) {
17203         return createRange(pos, range.end);
17204     }
17205     ts.moveRangePos = moveRangePos;
17206     /**
17207      * Moves the start position of a range past any decorators.
17208      */
17209     function moveRangePastDecorators(node) {
17210         return node.decorators && node.decorators.length > 0
17211             ? moveRangePos(node, node.decorators.end)
17212             : node;
17213     }
17214     ts.moveRangePastDecorators = moveRangePastDecorators;
17215     /**
17216      * Moves the start position of a range past any decorators or modifiers.
17217      */
17218     function moveRangePastModifiers(node) {
17219         return node.modifiers && node.modifiers.length > 0
17220             ? moveRangePos(node, node.modifiers.end)
17221             : moveRangePastDecorators(node);
17222     }
17223     ts.moveRangePastModifiers = moveRangePastModifiers;
17224     /**
17225      * Determines whether a TextRange has the same start and end positions.
17226      *
17227      * @param range A TextRange.
17228      */
17229     function isCollapsedRange(range) {
17230         return range.pos === range.end;
17231     }
17232     ts.isCollapsedRange = isCollapsedRange;
17233     /**
17234      * Creates a new TextRange for a token at the provides start position.
17235      *
17236      * @param pos The start position.
17237      * @param token The token.
17238      */
17239     function createTokenRange(pos, token) {
17240         return createRange(pos, pos + ts.tokenToString(token).length);
17241     }
17242     ts.createTokenRange = createTokenRange;
17243     function rangeIsOnSingleLine(range, sourceFile) {
17244         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17245     }
17246     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17247     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17248         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17249     }
17250     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17251     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17252         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17253     }
17254     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17255     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17256         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17257     }
17258     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17259     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17260         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17261     }
17262     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17263     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17264         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17265         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17266     }
17267     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17268     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17269         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17270     }
17271     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17272     function isNodeArrayMultiLine(list, sourceFile) {
17273         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17274     }
17275     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17276     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17277         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17278     }
17279     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17280     function getStartPositionOfRange(range, sourceFile, includeComments) {
17281         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17282     }
17283     ts.getStartPositionOfRange = getStartPositionOfRange;
17284     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17285         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17286         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17287         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17288     }
17289     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17290     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17291         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17292         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17293     }
17294     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17295     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17296         if (stopPos === void 0) { stopPos = 0; }
17297         while (pos-- > stopPos) {
17298             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17299                 return pos;
17300             }
17301         }
17302     }
17303     /**
17304      * Determines whether a name was originally the declaration name of an enum or namespace
17305      * declaration.
17306      */
17307     function isDeclarationNameOfEnumOrNamespace(node) {
17308         var parseNode = ts.getParseTreeNode(node);
17309         if (parseNode) {
17310             switch (parseNode.parent.kind) {
17311                 case 248 /* EnumDeclaration */:
17312                 case 249 /* ModuleDeclaration */:
17313                     return parseNode === parseNode.parent.name;
17314             }
17315         }
17316         return false;
17317     }
17318     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17319     function getInitializedVariables(node) {
17320         return ts.filter(node.declarations, isInitializedVariable);
17321     }
17322     ts.getInitializedVariables = getInitializedVariables;
17323     function isInitializedVariable(node) {
17324         return node.initializer !== undefined;
17325     }
17326     function isWatchSet(options) {
17327         // Firefox has Object.prototype.watch
17328         return options.watch && options.hasOwnProperty("watch");
17329     }
17330     ts.isWatchSet = isWatchSet;
17331     function closeFileWatcher(watcher) {
17332         watcher.close();
17333     }
17334     ts.closeFileWatcher = closeFileWatcher;
17335     function getCheckFlags(symbol) {
17336         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17337     }
17338     ts.getCheckFlags = getCheckFlags;
17339     function getDeclarationModifierFlagsFromSymbol(s) {
17340         if (s.valueDeclaration) {
17341             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17342             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17343         }
17344         if (getCheckFlags(s) & 6 /* Synthetic */) {
17345             var checkFlags = s.checkFlags;
17346             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17347                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17348                     16 /* Protected */;
17349             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17350             return accessModifier | staticModifier;
17351         }
17352         if (s.flags & 4194304 /* Prototype */) {
17353             return 4 /* Public */ | 32 /* Static */;
17354         }
17355         return 0;
17356     }
17357     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17358     function skipAlias(symbol, checker) {
17359         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17360     }
17361     ts.skipAlias = skipAlias;
17362     /** See comment on `declareModuleMember` in `binder.ts`. */
17363     function getCombinedLocalAndExportSymbolFlags(symbol) {
17364         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17365     }
17366     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17367     function isWriteOnlyAccess(node) {
17368         return accessKind(node) === 1 /* Write */;
17369     }
17370     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17371     function isWriteAccess(node) {
17372         return accessKind(node) !== 0 /* Read */;
17373     }
17374     ts.isWriteAccess = isWriteAccess;
17375     var AccessKind;
17376     (function (AccessKind) {
17377         /** Only reads from a variable. */
17378         AccessKind[AccessKind["Read"] = 0] = "Read";
17379         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17380         AccessKind[AccessKind["Write"] = 1] = "Write";
17381         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17382         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17383     })(AccessKind || (AccessKind = {}));
17384     function accessKind(node) {
17385         var parent = node.parent;
17386         if (!parent)
17387             return 0 /* Read */;
17388         switch (parent.kind) {
17389             case 200 /* ParenthesizedExpression */:
17390                 return accessKind(parent);
17391             case 208 /* PostfixUnaryExpression */:
17392             case 207 /* PrefixUnaryExpression */:
17393                 var operator = parent.operator;
17394                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17395             case 209 /* BinaryExpression */:
17396                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17397                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17398                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17399                     : 0 /* Read */;
17400             case 194 /* PropertyAccessExpression */:
17401                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17402             case 281 /* PropertyAssignment */: {
17403                 var parentAccess = accessKind(parent.parent);
17404                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17405                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17406             }
17407             case 282 /* ShorthandPropertyAssignment */:
17408                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17409                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17410             case 192 /* ArrayLiteralExpression */:
17411                 return accessKind(parent);
17412             default:
17413                 return 0 /* Read */;
17414         }
17415         function writeOrReadWrite() {
17416             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17417             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17418         }
17419     }
17420     function reverseAccessKind(a) {
17421         switch (a) {
17422             case 0 /* Read */:
17423                 return 1 /* Write */;
17424             case 1 /* Write */:
17425                 return 0 /* Read */;
17426             case 2 /* ReadWrite */:
17427                 return 2 /* ReadWrite */;
17428             default:
17429                 return ts.Debug.assertNever(a);
17430         }
17431     }
17432     function compareDataObjects(dst, src) {
17433         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17434             return false;
17435         }
17436         for (var e in dst) {
17437             if (typeof dst[e] === "object") {
17438                 if (!compareDataObjects(dst[e], src[e])) {
17439                     return false;
17440                 }
17441             }
17442             else if (typeof dst[e] !== "function") {
17443                 if (dst[e] !== src[e]) {
17444                     return false;
17445                 }
17446             }
17447         }
17448         return true;
17449     }
17450     ts.compareDataObjects = compareDataObjects;
17451     /**
17452      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17453      */
17454     function clearMap(map, onDeleteValue) {
17455         // Remove all
17456         map.forEach(onDeleteValue);
17457         map.clear();
17458     }
17459     ts.clearMap = clearMap;
17460     /**
17461      * Mutates the map with newMap such that keys in map will be same as newMap.
17462      */
17463     function mutateMapSkippingNewValues(map, newMap, options) {
17464         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17465         // Needs update
17466         map.forEach(function (existingValue, key) {
17467             var valueInNewMap = newMap.get(key);
17468             // Not present any more in new map, remove it
17469             if (valueInNewMap === undefined) {
17470                 map.delete(key);
17471                 onDeleteValue(existingValue, key);
17472             }
17473             // If present notify about existing values
17474             else if (onExistingValue) {
17475                 onExistingValue(existingValue, valueInNewMap, key);
17476             }
17477         });
17478     }
17479     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17480     /**
17481      * Mutates the map with newMap such that keys in map will be same as newMap.
17482      */
17483     function mutateMap(map, newMap, options) {
17484         // Needs update
17485         mutateMapSkippingNewValues(map, newMap, options);
17486         var createNewValue = options.createNewValue;
17487         // Add new values that are not already present
17488         newMap.forEach(function (valueInNewMap, key) {
17489             if (!map.has(key)) {
17490                 // New values
17491                 map.set(key, createNewValue(key, valueInNewMap));
17492             }
17493         });
17494     }
17495     ts.mutateMap = mutateMap;
17496     // Return true if the given type is the constructor type for an abstract class
17497     function isAbstractConstructorType(type) {
17498         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17499     }
17500     ts.isAbstractConstructorType = isAbstractConstructorType;
17501     function isAbstractConstructorSymbol(symbol) {
17502         if (symbol.flags & 32 /* Class */) {
17503             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17504             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17505         }
17506         return false;
17507     }
17508     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17509     function getClassLikeDeclarationOfSymbol(symbol) {
17510         return ts.find(symbol.declarations, ts.isClassLike);
17511     }
17512     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17513     function getObjectFlags(type) {
17514         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17515     }
17516     ts.getObjectFlags = getObjectFlags;
17517     function typeHasCallOrConstructSignatures(type, checker) {
17518         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17519     }
17520     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17521     function forSomeAncestorDirectory(directory, callback) {
17522         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17523     }
17524     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17525     function isUMDExportSymbol(symbol) {
17526         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17527     }
17528     ts.isUMDExportSymbol = isUMDExportSymbol;
17529     function showModuleSpecifier(_a) {
17530         var moduleSpecifier = _a.moduleSpecifier;
17531         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17532     }
17533     ts.showModuleSpecifier = showModuleSpecifier;
17534     function getLastChild(node) {
17535         var lastChild;
17536         ts.forEachChild(node, function (child) {
17537             if (nodeIsPresent(child))
17538                 lastChild = child;
17539         }, function (children) {
17540             // As an optimization, jump straight to the end of the list.
17541             for (var i = children.length - 1; i >= 0; i--) {
17542                 if (nodeIsPresent(children[i])) {
17543                     lastChild = children[i];
17544                     break;
17545                 }
17546             }
17547         });
17548         return lastChild;
17549     }
17550     ts.getLastChild = getLastChild;
17551     function addToSeen(seen, key, value) {
17552         if (value === void 0) { value = true; }
17553         key = String(key);
17554         if (seen.has(key)) {
17555             return false;
17556         }
17557         seen.set(key, value);
17558         return true;
17559     }
17560     ts.addToSeen = addToSeen;
17561     function isObjectTypeDeclaration(node) {
17562         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17563     }
17564     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17565     function isTypeNodeKind(kind) {
17566         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17567             || kind === 125 /* AnyKeyword */
17568             || kind === 148 /* UnknownKeyword */
17569             || kind === 140 /* NumberKeyword */
17570             || kind === 151 /* BigIntKeyword */
17571             || kind === 141 /* ObjectKeyword */
17572             || kind === 128 /* BooleanKeyword */
17573             || kind === 143 /* StringKeyword */
17574             || kind === 144 /* SymbolKeyword */
17575             || kind === 104 /* ThisKeyword */
17576             || kind === 110 /* VoidKeyword */
17577             || kind === 146 /* UndefinedKeyword */
17578             || kind === 100 /* NullKeyword */
17579             || kind === 137 /* NeverKeyword */
17580             || kind === 216 /* ExpressionWithTypeArguments */
17581             || kind === 295 /* JSDocAllType */
17582             || kind === 296 /* JSDocUnknownType */
17583             || kind === 297 /* JSDocNullableType */
17584             || kind === 298 /* JSDocNonNullableType */
17585             || kind === 299 /* JSDocOptionalType */
17586             || kind === 300 /* JSDocFunctionType */
17587             || kind === 301 /* JSDocVariadicType */;
17588     }
17589     ts.isTypeNodeKind = isTypeNodeKind;
17590     function isAccessExpression(node) {
17591         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17592     }
17593     ts.isAccessExpression = isAccessExpression;
17594     function getNameOfAccessExpression(node) {
17595         if (node.kind === 194 /* PropertyAccessExpression */) {
17596             return node.name;
17597         }
17598         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17599         return node.argumentExpression;
17600     }
17601     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17602     function isBundleFileTextLike(section) {
17603         switch (section.kind) {
17604             case "text" /* Text */:
17605             case "internal" /* Internal */:
17606                 return true;
17607             default:
17608                 return false;
17609         }
17610     }
17611     ts.isBundleFileTextLike = isBundleFileTextLike;
17612     function isNamedImportsOrExports(node) {
17613         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17614     }
17615     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17616     function Symbol(flags, name) {
17617         this.flags = flags;
17618         this.escapedName = name;
17619         this.declarations = undefined;
17620         this.valueDeclaration = undefined;
17621         this.id = undefined;
17622         this.mergeId = undefined;
17623         this.parent = undefined;
17624     }
17625     function Type(checker, flags) {
17626         this.flags = flags;
17627         if (ts.Debug.isDebugging) {
17628             this.checker = checker;
17629         }
17630     }
17631     function Signature(checker, flags) {
17632         this.flags = flags;
17633         if (ts.Debug.isDebugging) {
17634             this.checker = checker;
17635         }
17636     }
17637     function Node(kind, pos, end) {
17638         this.pos = pos;
17639         this.end = end;
17640         this.kind = kind;
17641         this.id = 0;
17642         this.flags = 0 /* None */;
17643         this.modifierFlagsCache = 0 /* None */;
17644         this.transformFlags = 0 /* None */;
17645         this.parent = undefined;
17646         this.original = undefined;
17647     }
17648     function Token(kind, pos, end) {
17649         this.pos = pos;
17650         this.end = end;
17651         this.kind = kind;
17652         this.id = 0;
17653         this.flags = 0 /* None */;
17654         this.transformFlags = 0 /* None */;
17655         this.parent = undefined;
17656     }
17657     function Identifier(kind, pos, end) {
17658         this.pos = pos;
17659         this.end = end;
17660         this.kind = kind;
17661         this.id = 0;
17662         this.flags = 0 /* None */;
17663         this.transformFlags = 0 /* None */;
17664         this.parent = undefined;
17665         this.original = undefined;
17666         this.flowNode = undefined;
17667     }
17668     function SourceMapSource(fileName, text, skipTrivia) {
17669         this.fileName = fileName;
17670         this.text = text;
17671         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17672     }
17673     // eslint-disable-next-line prefer-const
17674     ts.objectAllocator = {
17675         getNodeConstructor: function () { return Node; },
17676         getTokenConstructor: function () { return Token; },
17677         getIdentifierConstructor: function () { return Identifier; },
17678         getPrivateIdentifierConstructor: function () { return Node; },
17679         getSourceFileConstructor: function () { return Node; },
17680         getSymbolConstructor: function () { return Symbol; },
17681         getTypeConstructor: function () { return Type; },
17682         getSignatureConstructor: function () { return Signature; },
17683         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17684     };
17685     function setObjectAllocator(alloc) {
17686         ts.objectAllocator = alloc;
17687     }
17688     ts.setObjectAllocator = setObjectAllocator;
17689     function formatStringFromArgs(text, args, baseIndex) {
17690         if (baseIndex === void 0) { baseIndex = 0; }
17691         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17692     }
17693     ts.formatStringFromArgs = formatStringFromArgs;
17694     /* @internal */
17695     function setLocalizedDiagnosticMessages(messages) {
17696         ts.localizedDiagnosticMessages = messages;
17697     }
17698     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17699     function getLocaleSpecificMessage(message) {
17700         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17701     }
17702     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17703     function createFileDiagnostic(file, start, length, message) {
17704         ts.Debug.assertGreaterThanOrEqual(start, 0);
17705         ts.Debug.assertGreaterThanOrEqual(length, 0);
17706         if (file) {
17707             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17708             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17709         }
17710         var text = getLocaleSpecificMessage(message);
17711         if (arguments.length > 4) {
17712             text = formatStringFromArgs(text, arguments, 4);
17713         }
17714         return {
17715             file: file,
17716             start: start,
17717             length: length,
17718             messageText: text,
17719             category: message.category,
17720             code: message.code,
17721             reportsUnnecessary: message.reportsUnnecessary,
17722         };
17723     }
17724     ts.createFileDiagnostic = createFileDiagnostic;
17725     function formatMessage(_dummy, message) {
17726         var text = getLocaleSpecificMessage(message);
17727         if (arguments.length > 2) {
17728             text = formatStringFromArgs(text, arguments, 2);
17729         }
17730         return text;
17731     }
17732     ts.formatMessage = formatMessage;
17733     function createCompilerDiagnostic(message) {
17734         var text = getLocaleSpecificMessage(message);
17735         if (arguments.length > 1) {
17736             text = formatStringFromArgs(text, arguments, 1);
17737         }
17738         return {
17739             file: undefined,
17740             start: undefined,
17741             length: undefined,
17742             messageText: text,
17743             category: message.category,
17744             code: message.code,
17745             reportsUnnecessary: message.reportsUnnecessary,
17746         };
17747     }
17748     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17749     function createCompilerDiagnosticFromMessageChain(chain) {
17750         return {
17751             file: undefined,
17752             start: undefined,
17753             length: undefined,
17754             code: chain.code,
17755             category: chain.category,
17756             messageText: chain.next ? chain : chain.messageText,
17757         };
17758     }
17759     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17760     function chainDiagnosticMessages(details, message) {
17761         var text = getLocaleSpecificMessage(message);
17762         if (arguments.length > 2) {
17763             text = formatStringFromArgs(text, arguments, 2);
17764         }
17765         return {
17766             messageText: text,
17767             category: message.category,
17768             code: message.code,
17769             next: details === undefined || Array.isArray(details) ? details : [details]
17770         };
17771     }
17772     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17773     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17774         var lastChain = headChain;
17775         while (lastChain.next) {
17776             lastChain = lastChain.next[0];
17777         }
17778         lastChain.next = [tailChain];
17779     }
17780     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17781     function getDiagnosticFilePath(diagnostic) {
17782         return diagnostic.file ? diagnostic.file.path : undefined;
17783     }
17784     function compareDiagnostics(d1, d2) {
17785         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17786             compareRelatedInformation(d1, d2) ||
17787             0 /* EqualTo */;
17788     }
17789     ts.compareDiagnostics = compareDiagnostics;
17790     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17791         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17792             ts.compareValues(d1.start, d2.start) ||
17793             ts.compareValues(d1.length, d2.length) ||
17794             ts.compareValues(d1.code, d2.code) ||
17795             compareMessageText(d1.messageText, d2.messageText) ||
17796             0 /* EqualTo */;
17797     }
17798     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17799     function compareRelatedInformation(d1, d2) {
17800         if (!d1.relatedInformation && !d2.relatedInformation) {
17801             return 0 /* EqualTo */;
17802         }
17803         if (d1.relatedInformation && d2.relatedInformation) {
17804             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17805                 var d2i = d2.relatedInformation[index];
17806                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17807             }) || 0 /* EqualTo */;
17808         }
17809         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17810     }
17811     function compareMessageText(t1, t2) {
17812         if (typeof t1 === "string" && typeof t2 === "string") {
17813             return ts.compareStringsCaseSensitive(t1, t2);
17814         }
17815         else if (typeof t1 === "string") {
17816             return -1 /* LessThan */;
17817         }
17818         else if (typeof t2 === "string") {
17819             return 1 /* GreaterThan */;
17820         }
17821         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17822         if (res) {
17823             return res;
17824         }
17825         if (!t1.next && !t2.next) {
17826             return 0 /* EqualTo */;
17827         }
17828         if (!t1.next) {
17829             return -1 /* LessThan */;
17830         }
17831         if (!t2.next) {
17832             return 1 /* GreaterThan */;
17833         }
17834         var len = Math.min(t1.next.length, t2.next.length);
17835         for (var i = 0; i < len; i++) {
17836             res = compareMessageText(t1.next[i], t2.next[i]);
17837             if (res) {
17838                 return res;
17839             }
17840         }
17841         if (t1.next.length < t2.next.length) {
17842             return -1 /* LessThan */;
17843         }
17844         else if (t1.next.length > t2.next.length) {
17845             return 1 /* GreaterThan */;
17846         }
17847         return 0 /* EqualTo */;
17848     }
17849     function getEmitScriptTarget(compilerOptions) {
17850         return compilerOptions.target || 0 /* ES3 */;
17851     }
17852     ts.getEmitScriptTarget = getEmitScriptTarget;
17853     function getEmitModuleKind(compilerOptions) {
17854         return typeof compilerOptions.module === "number" ?
17855             compilerOptions.module :
17856             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17857     }
17858     ts.getEmitModuleKind = getEmitModuleKind;
17859     function getEmitModuleResolutionKind(compilerOptions) {
17860         var moduleResolution = compilerOptions.moduleResolution;
17861         if (moduleResolution === undefined) {
17862             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17863         }
17864         return moduleResolution;
17865     }
17866     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17867     function hasJsonModuleEmitEnabled(options) {
17868         switch (getEmitModuleKind(options)) {
17869             case ts.ModuleKind.CommonJS:
17870             case ts.ModuleKind.AMD:
17871             case ts.ModuleKind.ES2015:
17872             case ts.ModuleKind.ES2020:
17873             case ts.ModuleKind.ESNext:
17874                 return true;
17875             default:
17876                 return false;
17877         }
17878     }
17879     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17880     function unreachableCodeIsError(options) {
17881         return options.allowUnreachableCode === false;
17882     }
17883     ts.unreachableCodeIsError = unreachableCodeIsError;
17884     function unusedLabelIsError(options) {
17885         return options.allowUnusedLabels === false;
17886     }
17887     ts.unusedLabelIsError = unusedLabelIsError;
17888     function getAreDeclarationMapsEnabled(options) {
17889         return !!(getEmitDeclarations(options) && options.declarationMap);
17890     }
17891     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17892     function getAllowSyntheticDefaultImports(compilerOptions) {
17893         var moduleKind = getEmitModuleKind(compilerOptions);
17894         return compilerOptions.allowSyntheticDefaultImports !== undefined
17895             ? compilerOptions.allowSyntheticDefaultImports
17896             : compilerOptions.esModuleInterop ||
17897                 moduleKind === ts.ModuleKind.System;
17898     }
17899     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17900     function getEmitDeclarations(compilerOptions) {
17901         return !!(compilerOptions.declaration || compilerOptions.composite);
17902     }
17903     ts.getEmitDeclarations = getEmitDeclarations;
17904     function isIncrementalCompilation(options) {
17905         return !!(options.incremental || options.composite);
17906     }
17907     ts.isIncrementalCompilation = isIncrementalCompilation;
17908     function getStrictOptionValue(compilerOptions, flag) {
17909         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
17910     }
17911     ts.getStrictOptionValue = getStrictOptionValue;
17912     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
17913         return oldOptions !== newOptions &&
17914             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17915     }
17916     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
17917     function compilerOptionsAffectEmit(newOptions, oldOptions) {
17918         return oldOptions !== newOptions &&
17919             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17920     }
17921     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
17922     function getCompilerOptionValue(options, option) {
17923         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
17924     }
17925     ts.getCompilerOptionValue = getCompilerOptionValue;
17926     function hasZeroOrOneAsteriskCharacter(str) {
17927         var seenAsterisk = false;
17928         for (var i = 0; i < str.length; i++) {
17929             if (str.charCodeAt(i) === 42 /* asterisk */) {
17930                 if (!seenAsterisk) {
17931                     seenAsterisk = true;
17932                 }
17933                 else {
17934                     // have already seen asterisk
17935                     return false;
17936                 }
17937             }
17938         }
17939         return true;
17940     }
17941     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
17942     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
17943         var result = ts.createMap();
17944         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
17945             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
17946                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
17947             })));
17948         }));
17949         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
17950             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
17951             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
17952             result.set(commonOriginal, commonResolved);
17953         }
17954         return result;
17955     }
17956     ts.discoverProbableSymlinks = discoverProbableSymlinks;
17957     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
17958         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
17959         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
17960         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
17961             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
17962             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
17963             aParts.pop();
17964             bParts.pop();
17965         }
17966         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
17967     }
17968     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
17969     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
17970     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
17971         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
17972     }
17973     function stripLeadingDirectorySeparator(s) {
17974         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
17975     }
17976     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
17977         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
17978         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
17979     }
17980     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
17981     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
17982     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
17983     // proof.
17984     var reservedCharacterPattern = /[^\w\s\/]/g;
17985     function regExpEscape(text) {
17986         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
17987     }
17988     ts.regExpEscape = regExpEscape;
17989     function escapeRegExpCharacter(match) {
17990         return "\\" + match;
17991     }
17992     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
17993     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
17994     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
17995     var filesMatcher = {
17996         /**
17997          * Matches any single directory segment unless it is the last segment and a .min.js file
17998          * Breakdown:
17999          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18000          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18001          */
18002         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18003         /**
18004          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18005          * files or directories, does not match subdirectories that start with a . character
18006          */
18007         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18008         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18009     };
18010     var directoriesMatcher = {
18011         singleAsteriskRegexFragment: "[^/]*",
18012         /**
18013          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18014          * files or directories, does not match subdirectories that start with a . character
18015          */
18016         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18017         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18018     };
18019     var excludeMatcher = {
18020         singleAsteriskRegexFragment: "[^/]*",
18021         doubleAsteriskRegexFragment: "(/.+?)?",
18022         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18023     };
18024     var wildcardMatchers = {
18025         files: filesMatcher,
18026         directories: directoriesMatcher,
18027         exclude: excludeMatcher
18028     };
18029     function getRegularExpressionForWildcard(specs, basePath, usage) {
18030         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18031         if (!patterns || !patterns.length) {
18032             return undefined;
18033         }
18034         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18035         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18036         var terminator = usage === "exclude" ? "($|/)" : "$";
18037         return "^(" + pattern + ")" + terminator;
18038     }
18039     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18040     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18041         if (specs === undefined || specs.length === 0) {
18042             return undefined;
18043         }
18044         return ts.flatMap(specs, function (spec) {
18045             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18046         });
18047     }
18048     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18049     /**
18050      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18051      * and does not contain any glob characters itself.
18052      */
18053     function isImplicitGlob(lastPathComponent) {
18054         return !/[.*?]/.test(lastPathComponent);
18055     }
18056     ts.isImplicitGlob = isImplicitGlob;
18057     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18058         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18059         var subpattern = "";
18060         var hasWrittenComponent = false;
18061         var components = ts.getNormalizedPathComponents(spec, basePath);
18062         var lastComponent = ts.last(components);
18063         if (usage !== "exclude" && lastComponent === "**") {
18064             return undefined;
18065         }
18066         // getNormalizedPathComponents includes the separator for the root component.
18067         // We need to remove to create our regex correctly.
18068         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18069         if (isImplicitGlob(lastComponent)) {
18070             components.push("**", "*");
18071         }
18072         var optionalCount = 0;
18073         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18074             var component = components_1[_i];
18075             if (component === "**") {
18076                 subpattern += doubleAsteriskRegexFragment;
18077             }
18078             else {
18079                 if (usage === "directories") {
18080                     subpattern += "(";
18081                     optionalCount++;
18082                 }
18083                 if (hasWrittenComponent) {
18084                     subpattern += ts.directorySeparator;
18085                 }
18086                 if (usage !== "exclude") {
18087                     var componentPattern = "";
18088                     // The * and ? wildcards should not match directories or files that start with . if they
18089                     // appear first in a component. Dotted directories and files can be included explicitly
18090                     // like so: **/.*/.*
18091                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18092                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18093                         component = component.substr(1);
18094                     }
18095                     else if (component.charCodeAt(0) === 63 /* question */) {
18096                         componentPattern += "[^./]";
18097                         component = component.substr(1);
18098                     }
18099                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18100                     // Patterns should not include subfolders like node_modules unless they are
18101                     // explicitly included as part of the path.
18102                     //
18103                     // As an optimization, if the component pattern is the same as the component,
18104                     // then there definitely were no wildcard characters and we do not need to
18105                     // add the exclusion pattern.
18106                     if (componentPattern !== component) {
18107                         subpattern += implicitExcludePathRegexPattern;
18108                     }
18109                     subpattern += componentPattern;
18110                 }
18111                 else {
18112                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18113                 }
18114             }
18115             hasWrittenComponent = true;
18116         }
18117         while (optionalCount > 0) {
18118             subpattern += ")?";
18119             optionalCount--;
18120         }
18121         return subpattern;
18122     }
18123     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18124         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18125     }
18126     /** @param path directory of the tsconfig.json */
18127     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18128         path = ts.normalizePath(path);
18129         currentDirectory = ts.normalizePath(currentDirectory);
18130         var absolutePath = ts.combinePaths(currentDirectory, path);
18131         return {
18132             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18133             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18134             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18135             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18136             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18137         };
18138     }
18139     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18140     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18141         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18142     }
18143     ts.getRegexFromPattern = getRegexFromPattern;
18144     /** @param path directory of the tsconfig.json */
18145     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18146         path = ts.normalizePath(path);
18147         currentDirectory = ts.normalizePath(currentDirectory);
18148         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18149         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18150         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18151         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18152         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18153         // If there are no "includes", then just put everything in results[0].
18154         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18155         var visited = ts.createMap();
18156         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18157         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18158             var basePath = _a[_i];
18159             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18160         }
18161         return ts.flatten(results);
18162         function visitDirectory(path, absolutePath, depth) {
18163             var canonicalPath = toCanonical(realpath(absolutePath));
18164             if (visited.has(canonicalPath))
18165                 return;
18166             visited.set(canonicalPath, true);
18167             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18168             var _loop_1 = function (current) {
18169                 var name = ts.combinePaths(path, current);
18170                 var absoluteName = ts.combinePaths(absolutePath, current);
18171                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18172                     return "continue";
18173                 if (excludeRegex && excludeRegex.test(absoluteName))
18174                     return "continue";
18175                 if (!includeFileRegexes) {
18176                     results[0].push(name);
18177                 }
18178                 else {
18179                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18180                     if (includeIndex !== -1) {
18181                         results[includeIndex].push(name);
18182                     }
18183                 }
18184             };
18185             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18186                 var current = _b[_i];
18187                 _loop_1(current);
18188             }
18189             if (depth !== undefined) {
18190                 depth--;
18191                 if (depth === 0) {
18192                     return;
18193                 }
18194             }
18195             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18196                 var current = _d[_c];
18197                 var name = ts.combinePaths(path, current);
18198                 var absoluteName = ts.combinePaths(absolutePath, current);
18199                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18200                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18201                     visitDirectory(name, absoluteName, depth);
18202                 }
18203             }
18204         }
18205     }
18206     ts.matchFiles = matchFiles;
18207     /**
18208      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18209      */
18210     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18211         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18212         var basePaths = [path];
18213         if (includes) {
18214             // Storage for literal base paths amongst the include patterns.
18215             var includeBasePaths = [];
18216             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18217                 var include = includes_1[_i];
18218                 // We also need to check the relative paths by converting them to absolute and normalizing
18219                 // in case they escape the base path (e.g "..\somedirectory")
18220                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18221                 // Append the literal and canonical candidate base paths.
18222                 includeBasePaths.push(getIncludeBasePath(absolute));
18223             }
18224             // Sort the offsets array using either the literal or canonical path representations.
18225             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18226             var _loop_2 = function (includeBasePath) {
18227                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18228                     basePaths.push(includeBasePath);
18229                 }
18230             };
18231             // Iterate over each include base path and include unique base paths that are not a
18232             // subpath of an existing base path
18233             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18234                 var includeBasePath = includeBasePaths_1[_a];
18235                 _loop_2(includeBasePath);
18236             }
18237         }
18238         return basePaths;
18239     }
18240     function getIncludeBasePath(absolute) {
18241         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18242         if (wildcardOffset < 0) {
18243             // No "*" or "?" in the path
18244             return !ts.hasExtension(absolute)
18245                 ? absolute
18246                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18247         }
18248         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18249     }
18250     function ensureScriptKind(fileName, scriptKind) {
18251         // Using scriptKind as a condition handles both:
18252         // - 'scriptKind' is unspecified and thus it is `undefined`
18253         // - 'scriptKind' is set and it is `Unknown` (0)
18254         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18255         // to get the ScriptKind from the file name. If it cannot be resolved
18256         // from the file name then the default 'TS' script kind is returned.
18257         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18258     }
18259     ts.ensureScriptKind = ensureScriptKind;
18260     function getScriptKindFromFileName(fileName) {
18261         var ext = fileName.substr(fileName.lastIndexOf("."));
18262         switch (ext.toLowerCase()) {
18263             case ".js" /* Js */:
18264                 return 1 /* JS */;
18265             case ".jsx" /* Jsx */:
18266                 return 2 /* JSX */;
18267             case ".ts" /* Ts */:
18268                 return 3 /* TS */;
18269             case ".tsx" /* Tsx */:
18270                 return 4 /* TSX */;
18271             case ".json" /* Json */:
18272                 return 6 /* JSON */;
18273             default:
18274                 return 0 /* Unknown */;
18275         }
18276     }
18277     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18278     /**
18279      *  List of supported extensions in order of file resolution precedence.
18280      */
18281     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18282     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18283     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18284     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18285     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18286     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18287     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18288     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18289     function getSupportedExtensions(options, extraFileExtensions) {
18290         var needJsExtensions = options && options.allowJs;
18291         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18292             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18293         }
18294         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18295         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18296     }
18297     ts.getSupportedExtensions = getSupportedExtensions;
18298     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18299         if (!options || !options.resolveJsonModule) {
18300             return supportedExtensions;
18301         }
18302         if (supportedExtensions === allSupportedExtensions) {
18303             return allSupportedExtensionsWithJson;
18304         }
18305         if (supportedExtensions === ts.supportedTSExtensions) {
18306             return ts.supportedTSExtensionsWithJson;
18307         }
18308         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18309     }
18310     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18311     function isJSLike(scriptKind) {
18312         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18313     }
18314     function hasJSFileExtension(fileName) {
18315         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18316     }
18317     ts.hasJSFileExtension = hasJSFileExtension;
18318     function hasTSFileExtension(fileName) {
18319         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18320     }
18321     ts.hasTSFileExtension = hasTSFileExtension;
18322     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18323         if (!fileName) {
18324             return false;
18325         }
18326         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18327         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18328             var extension = _a[_i];
18329             if (ts.fileExtensionIs(fileName, extension)) {
18330                 return true;
18331             }
18332         }
18333         return false;
18334     }
18335     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18336     /**
18337      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18338      * aligned to the offset of the highest priority extension in the
18339      * allSupportedExtensions array.
18340      */
18341     var ExtensionPriority;
18342     (function (ExtensionPriority) {
18343         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18344         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18345         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18346         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18347     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18348     function getExtensionPriority(path, supportedExtensions) {
18349         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18350             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18351                 return adjustExtensionPriority(i, supportedExtensions);
18352             }
18353         }
18354         // If its not in the list of supported extensions, this is likely a
18355         // TypeScript file with a non-ts extension
18356         return 0 /* Highest */;
18357     }
18358     ts.getExtensionPriority = getExtensionPriority;
18359     /**
18360      * Adjusts an extension priority to be the highest priority within the same range.
18361      */
18362     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18363         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18364             return 0 /* TypeScriptFiles */;
18365         }
18366         else if (extensionPriority < supportedExtensions.length) {
18367             return 2 /* DeclarationAndJavaScriptFiles */;
18368         }
18369         else {
18370             return supportedExtensions.length;
18371         }
18372     }
18373     ts.adjustExtensionPriority = adjustExtensionPriority;
18374     /**
18375      * Gets the next lowest extension priority for a given priority.
18376      */
18377     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18378         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18379             return 2 /* DeclarationAndJavaScriptFiles */;
18380         }
18381         else {
18382             return supportedExtensions.length;
18383         }
18384     }
18385     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18386     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18387     function removeFileExtension(path) {
18388         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18389             var ext = extensionsToRemove_1[_i];
18390             var extensionless = tryRemoveExtension(path, ext);
18391             if (extensionless !== undefined) {
18392                 return extensionless;
18393             }
18394         }
18395         return path;
18396     }
18397     ts.removeFileExtension = removeFileExtension;
18398     function tryRemoveExtension(path, extension) {
18399         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18400     }
18401     ts.tryRemoveExtension = tryRemoveExtension;
18402     function removeExtension(path, extension) {
18403         return path.substring(0, path.length - extension.length);
18404     }
18405     ts.removeExtension = removeExtension;
18406     function changeExtension(path, newExtension) {
18407         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18408     }
18409     ts.changeExtension = changeExtension;
18410     function tryParsePattern(pattern) {
18411         // This should be verified outside of here and a proper error thrown.
18412         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18413         var indexOfStar = pattern.indexOf("*");
18414         return indexOfStar === -1 ? undefined : {
18415             prefix: pattern.substr(0, indexOfStar),
18416             suffix: pattern.substr(indexOfStar + 1)
18417         };
18418     }
18419     ts.tryParsePattern = tryParsePattern;
18420     function positionIsSynthesized(pos) {
18421         // This is a fast way of testing the following conditions:
18422         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18423         return !(pos >= 0);
18424     }
18425     ts.positionIsSynthesized = positionIsSynthesized;
18426     /** True if an extension is one of the supported TypeScript extensions. */
18427     function extensionIsTS(ext) {
18428         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18429     }
18430     ts.extensionIsTS = extensionIsTS;
18431     function resolutionExtensionIsTSOrJson(ext) {
18432         return extensionIsTS(ext) || ext === ".json" /* Json */;
18433     }
18434     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18435     /**
18436      * Gets the extension from a path.
18437      * Path must have a valid extension.
18438      */
18439     function extensionFromPath(path) {
18440         var ext = tryGetExtensionFromPath(path);
18441         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18442     }
18443     ts.extensionFromPath = extensionFromPath;
18444     function isAnySupportedFileExtension(path) {
18445         return tryGetExtensionFromPath(path) !== undefined;
18446     }
18447     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18448     function tryGetExtensionFromPath(path) {
18449         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18450     }
18451     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18452     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18453         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18454     }
18455     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18456     ts.emptyFileSystemEntries = {
18457         files: ts.emptyArray,
18458         directories: ts.emptyArray
18459     };
18460     /**
18461      * patternStrings contains both pattern strings (containing "*") and regular strings.
18462      * Return an exact match if possible, or a pattern match, or undefined.
18463      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18464      */
18465     function matchPatternOrExact(patternStrings, candidate) {
18466         var patterns = [];
18467         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18468             var patternString = patternStrings_1[_i];
18469             if (!hasZeroOrOneAsteriskCharacter(patternString))
18470                 continue;
18471             var pattern = tryParsePattern(patternString);
18472             if (pattern) {
18473                 patterns.push(pattern);
18474             }
18475             else if (patternString === candidate) {
18476                 // pattern was matched as is - no need to search further
18477                 return patternString;
18478             }
18479         }
18480         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18481     }
18482     ts.matchPatternOrExact = matchPatternOrExact;
18483     function sliceAfter(arr, value) {
18484         var index = arr.indexOf(value);
18485         ts.Debug.assert(index !== -1);
18486         return arr.slice(index);
18487     }
18488     ts.sliceAfter = sliceAfter;
18489     function addRelatedInfo(diagnostic) {
18490         var _a;
18491         var relatedInformation = [];
18492         for (var _i = 1; _i < arguments.length; _i++) {
18493             relatedInformation[_i - 1] = arguments[_i];
18494         }
18495         if (!relatedInformation.length) {
18496             return diagnostic;
18497         }
18498         if (!diagnostic.relatedInformation) {
18499             diagnostic.relatedInformation = [];
18500         }
18501         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18502         return diagnostic;
18503     }
18504     ts.addRelatedInfo = addRelatedInfo;
18505     function minAndMax(arr, getValue) {
18506         ts.Debug.assert(arr.length !== 0);
18507         var min = getValue(arr[0]);
18508         var max = min;
18509         for (var i = 1; i < arr.length; i++) {
18510             var value = getValue(arr[i]);
18511             if (value < min) {
18512                 min = value;
18513             }
18514             else if (value > max) {
18515                 max = value;
18516             }
18517         }
18518         return { min: min, max: max };
18519     }
18520     ts.minAndMax = minAndMax;
18521     var NodeSet = /** @class */ (function () {
18522         function NodeSet() {
18523             this.map = ts.createMap();
18524         }
18525         NodeSet.prototype.add = function (node) {
18526             this.map.set(String(ts.getNodeId(node)), node);
18527         };
18528         NodeSet.prototype.tryAdd = function (node) {
18529             if (this.has(node))
18530                 return false;
18531             this.add(node);
18532             return true;
18533         };
18534         NodeSet.prototype.has = function (node) {
18535             return this.map.has(String(ts.getNodeId(node)));
18536         };
18537         NodeSet.prototype.forEach = function (cb) {
18538             this.map.forEach(cb);
18539         };
18540         NodeSet.prototype.some = function (pred) {
18541             return forEachEntry(this.map, pred) || false;
18542         };
18543         return NodeSet;
18544     }());
18545     ts.NodeSet = NodeSet;
18546     var NodeMap = /** @class */ (function () {
18547         function NodeMap() {
18548             this.map = ts.createMap();
18549         }
18550         NodeMap.prototype.get = function (node) {
18551             var res = this.map.get(String(ts.getNodeId(node)));
18552             return res && res.value;
18553         };
18554         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18555             var res = this.get(node);
18556             if (res)
18557                 return res;
18558             var value = setValue();
18559             this.set(node, value);
18560             return value;
18561         };
18562         NodeMap.prototype.set = function (node, value) {
18563             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18564         };
18565         NodeMap.prototype.has = function (node) {
18566             return this.map.has(String(ts.getNodeId(node)));
18567         };
18568         NodeMap.prototype.forEach = function (cb) {
18569             this.map.forEach(function (_a) {
18570                 var node = _a.node, value = _a.value;
18571                 return cb(value, node);
18572             });
18573         };
18574         return NodeMap;
18575     }());
18576     ts.NodeMap = NodeMap;
18577     function rangeOfNode(node) {
18578         return { pos: getTokenPosOfNode(node), end: node.end };
18579     }
18580     ts.rangeOfNode = rangeOfNode;
18581     function rangeOfTypeParameters(typeParameters) {
18582         // Include the `<>`
18583         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18584     }
18585     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18586     function skipTypeChecking(sourceFile, options, host) {
18587         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18588         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18589         // '/// <reference no-default-lib="true"/>' directive.
18590         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18591             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18592             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18593     }
18594     ts.skipTypeChecking = skipTypeChecking;
18595     function isJsonEqual(a, b) {
18596         // eslint-disable-next-line no-null/no-null
18597         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18598     }
18599     ts.isJsonEqual = isJsonEqual;
18600     function getOrUpdate(map, key, getDefault) {
18601         var got = map.get(key);
18602         if (got === undefined) {
18603             var value = getDefault();
18604             map.set(key, value);
18605             return value;
18606         }
18607         else {
18608             return got;
18609         }
18610     }
18611     ts.getOrUpdate = getOrUpdate;
18612     /**
18613      * Converts a bigint literal string, e.g. `0x1234n`,
18614      * to its decimal string representation, e.g. `4660`.
18615      */
18616     function parsePseudoBigInt(stringValue) {
18617         var log2Base;
18618         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18619             case 98 /* b */:
18620             case 66 /* B */: // 0b or 0B
18621                 log2Base = 1;
18622                 break;
18623             case 111 /* o */:
18624             case 79 /* O */: // 0o or 0O
18625                 log2Base = 3;
18626                 break;
18627             case 120 /* x */:
18628             case 88 /* X */: // 0x or 0X
18629                 log2Base = 4;
18630                 break;
18631             default: // already in decimal; omit trailing "n"
18632                 var nIndex = stringValue.length - 1;
18633                 // Skip leading 0s
18634                 var nonZeroStart = 0;
18635                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18636                     nonZeroStart++;
18637                 }
18638                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18639         }
18640         // Omit leading "0b", "0o", or "0x", and trailing "n"
18641         var startIndex = 2, endIndex = stringValue.length - 1;
18642         var bitsNeeded = (endIndex - startIndex) * log2Base;
18643         // Stores the value specified by the string as a LE array of 16-bit integers
18644         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18645         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18646         // Add the digits, one at a time
18647         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18648             var segment = bitOffset >>> 4;
18649             var digitChar = stringValue.charCodeAt(i);
18650             // Find character range: 0-9 < A-F < a-f
18651             var digit = digitChar <= 57 /* _9 */
18652                 ? digitChar - 48 /* _0 */
18653                 : 10 + digitChar -
18654                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18655             var shiftedDigit = digit << (bitOffset & 15);
18656             segments[segment] |= shiftedDigit;
18657             var residual = shiftedDigit >>> 16;
18658             if (residual)
18659                 segments[segment + 1] |= residual; // overflows segment
18660         }
18661         // Repeatedly divide segments by 10 and add remainder to base10Value
18662         var base10Value = "";
18663         var firstNonzeroSegment = segments.length - 1;
18664         var segmentsRemaining = true;
18665         while (segmentsRemaining) {
18666             var mod10 = 0;
18667             segmentsRemaining = false;
18668             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18669                 var newSegment = mod10 << 16 | segments[segment];
18670                 var segmentValue = (newSegment / 10) | 0;
18671                 segments[segment] = segmentValue;
18672                 mod10 = newSegment - segmentValue * 10;
18673                 if (segmentValue && !segmentsRemaining) {
18674                     firstNonzeroSegment = segment;
18675                     segmentsRemaining = true;
18676                 }
18677             }
18678             base10Value = mod10 + base10Value;
18679         }
18680         return base10Value;
18681     }
18682     ts.parsePseudoBigInt = parsePseudoBigInt;
18683     function pseudoBigIntToString(_a) {
18684         var negative = _a.negative, base10Value = _a.base10Value;
18685         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18686     }
18687     ts.pseudoBigIntToString = pseudoBigIntToString;
18688     function isValidTypeOnlyAliasUseSite(useSite) {
18689         return !!(useSite.flags & 8388608 /* Ambient */)
18690             || isPartOfTypeQuery(useSite)
18691             || isIdentifierInNonEmittingHeritageClause(useSite)
18692             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18693             || !isExpressionNode(useSite);
18694     }
18695     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18696     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18697         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18698     }
18699     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18700     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18701         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18702             node = node.parent;
18703         }
18704         if (node.kind !== 154 /* ComputedPropertyName */) {
18705             return false;
18706         }
18707         if (hasModifier(node.parent, 128 /* Abstract */)) {
18708             return true;
18709         }
18710         var containerKind = node.parent.parent.kind;
18711         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18712     }
18713     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18714     function isIdentifierInNonEmittingHeritageClause(node) {
18715         if (node.kind !== 75 /* Identifier */)
18716             return false;
18717         var heritageClause = findAncestor(node.parent, function (parent) {
18718             switch (parent.kind) {
18719                 case 279 /* HeritageClause */:
18720                     return true;
18721                 case 194 /* PropertyAccessExpression */:
18722                 case 216 /* ExpressionWithTypeArguments */:
18723                     return false;
18724                 default:
18725                     return "quit";
18726             }
18727         });
18728         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18729     }
18730     function isIdentifierTypeReference(node) {
18731         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18732     }
18733     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18734     function arrayIsHomogeneous(array, comparer) {
18735         if (comparer === void 0) { comparer = ts.equateValues; }
18736         if (array.length < 2)
18737             return true;
18738         var first = array[0];
18739         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18740             var target = array[i];
18741             if (!comparer(first, target))
18742                 return false;
18743         }
18744         return true;
18745     }
18746     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18747 })(ts || (ts = {}));
18748 var ts;
18749 (function (ts) {
18750     var SignatureFlags;
18751     (function (SignatureFlags) {
18752         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18753         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18754         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18755         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18756         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18757         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18758     })(SignatureFlags || (SignatureFlags = {}));
18759     var NodeConstructor;
18760     var TokenConstructor;
18761     var IdentifierConstructor;
18762     var PrivateIdentifierConstructor;
18763     var SourceFileConstructor;
18764     function createNode(kind, pos, end) {
18765         if (kind === 290 /* SourceFile */) {
18766             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18767         }
18768         else if (kind === 75 /* Identifier */) {
18769             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18770         }
18771         else if (kind === 76 /* PrivateIdentifier */) {
18772             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18773         }
18774         else if (!ts.isNodeKind(kind)) {
18775             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18776         }
18777         else {
18778             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18779         }
18780     }
18781     ts.createNode = createNode;
18782     function visitNode(cbNode, node) {
18783         return node && cbNode(node);
18784     }
18785     function visitNodes(cbNode, cbNodes, nodes) {
18786         if (nodes) {
18787             if (cbNodes) {
18788                 return cbNodes(nodes);
18789             }
18790             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18791                 var node = nodes_1[_i];
18792                 var result = cbNode(node);
18793                 if (result) {
18794                     return result;
18795                 }
18796             }
18797         }
18798     }
18799     /*@internal*/
18800     function isJSDocLikeText(text, start) {
18801         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18802             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18803             text.charCodeAt(start + 3) !== 47 /* slash */;
18804     }
18805     ts.isJSDocLikeText = isJSDocLikeText;
18806     /**
18807      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18808      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18809      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18810      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18811      *
18812      * @param node a given node to visit its children
18813      * @param cbNode a callback to be invoked for all child nodes
18814      * @param cbNodes a callback to be invoked for embedded array
18815      *
18816      * @remarks `forEachChild` must visit the children of a node in the order
18817      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18818      */
18819     function forEachChild(node, cbNode, cbNodes) {
18820         if (!node || node.kind <= 152 /* LastToken */) {
18821             return;
18822         }
18823         switch (node.kind) {
18824             case 153 /* QualifiedName */:
18825                 return visitNode(cbNode, node.left) ||
18826                     visitNode(cbNode, node.right);
18827             case 155 /* TypeParameter */:
18828                 return visitNode(cbNode, node.name) ||
18829                     visitNode(cbNode, node.constraint) ||
18830                     visitNode(cbNode, node.default) ||
18831                     visitNode(cbNode, node.expression);
18832             case 282 /* ShorthandPropertyAssignment */:
18833                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18834                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18835                     visitNode(cbNode, node.name) ||
18836                     visitNode(cbNode, node.questionToken) ||
18837                     visitNode(cbNode, node.exclamationToken) ||
18838                     visitNode(cbNode, node.equalsToken) ||
18839                     visitNode(cbNode, node.objectAssignmentInitializer);
18840             case 283 /* SpreadAssignment */:
18841                 return visitNode(cbNode, node.expression);
18842             case 156 /* Parameter */:
18843                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18844                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18845                     visitNode(cbNode, node.dotDotDotToken) ||
18846                     visitNode(cbNode, node.name) ||
18847                     visitNode(cbNode, node.questionToken) ||
18848                     visitNode(cbNode, node.type) ||
18849                     visitNode(cbNode, node.initializer);
18850             case 159 /* PropertyDeclaration */:
18851                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18852                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18853                     visitNode(cbNode, node.name) ||
18854                     visitNode(cbNode, node.questionToken) ||
18855                     visitNode(cbNode, node.exclamationToken) ||
18856                     visitNode(cbNode, node.type) ||
18857                     visitNode(cbNode, node.initializer);
18858             case 158 /* PropertySignature */:
18859                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18860                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18861                     visitNode(cbNode, node.name) ||
18862                     visitNode(cbNode, node.questionToken) ||
18863                     visitNode(cbNode, node.type) ||
18864                     visitNode(cbNode, node.initializer);
18865             case 281 /* PropertyAssignment */:
18866                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18867                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18868                     visitNode(cbNode, node.name) ||
18869                     visitNode(cbNode, node.questionToken) ||
18870                     visitNode(cbNode, node.initializer);
18871             case 242 /* VariableDeclaration */:
18872                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18873                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18874                     visitNode(cbNode, node.name) ||
18875                     visitNode(cbNode, node.exclamationToken) ||
18876                     visitNode(cbNode, node.type) ||
18877                     visitNode(cbNode, node.initializer);
18878             case 191 /* BindingElement */:
18879                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18880                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18881                     visitNode(cbNode, node.dotDotDotToken) ||
18882                     visitNode(cbNode, node.propertyName) ||
18883                     visitNode(cbNode, node.name) ||
18884                     visitNode(cbNode, node.initializer);
18885             case 170 /* FunctionType */:
18886             case 171 /* ConstructorType */:
18887             case 165 /* CallSignature */:
18888             case 166 /* ConstructSignature */:
18889             case 167 /* IndexSignature */:
18890                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18891                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18892                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18893                     visitNodes(cbNode, cbNodes, node.parameters) ||
18894                     visitNode(cbNode, node.type);
18895             case 161 /* MethodDeclaration */:
18896             case 160 /* MethodSignature */:
18897             case 162 /* Constructor */:
18898             case 163 /* GetAccessor */:
18899             case 164 /* SetAccessor */:
18900             case 201 /* FunctionExpression */:
18901             case 244 /* FunctionDeclaration */:
18902             case 202 /* ArrowFunction */:
18903                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18904                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18905                     visitNode(cbNode, node.asteriskToken) ||
18906                     visitNode(cbNode, node.name) ||
18907                     visitNode(cbNode, node.questionToken) ||
18908                     visitNode(cbNode, node.exclamationToken) ||
18909                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18910                     visitNodes(cbNode, cbNodes, node.parameters) ||
18911                     visitNode(cbNode, node.type) ||
18912                     visitNode(cbNode, node.equalsGreaterThanToken) ||
18913                     visitNode(cbNode, node.body);
18914             case 169 /* TypeReference */:
18915                 return visitNode(cbNode, node.typeName) ||
18916                     visitNodes(cbNode, cbNodes, node.typeArguments);
18917             case 168 /* TypePredicate */:
18918                 return visitNode(cbNode, node.assertsModifier) ||
18919                     visitNode(cbNode, node.parameterName) ||
18920                     visitNode(cbNode, node.type);
18921             case 172 /* TypeQuery */:
18922                 return visitNode(cbNode, node.exprName);
18923             case 173 /* TypeLiteral */:
18924                 return visitNodes(cbNode, cbNodes, node.members);
18925             case 174 /* ArrayType */:
18926                 return visitNode(cbNode, node.elementType);
18927             case 175 /* TupleType */:
18928                 return visitNodes(cbNode, cbNodes, node.elementTypes);
18929             case 178 /* UnionType */:
18930             case 179 /* IntersectionType */:
18931                 return visitNodes(cbNode, cbNodes, node.types);
18932             case 180 /* ConditionalType */:
18933                 return visitNode(cbNode, node.checkType) ||
18934                     visitNode(cbNode, node.extendsType) ||
18935                     visitNode(cbNode, node.trueType) ||
18936                     visitNode(cbNode, node.falseType);
18937             case 181 /* InferType */:
18938                 return visitNode(cbNode, node.typeParameter);
18939             case 188 /* ImportType */:
18940                 return visitNode(cbNode, node.argument) ||
18941                     visitNode(cbNode, node.qualifier) ||
18942                     visitNodes(cbNode, cbNodes, node.typeArguments);
18943             case 182 /* ParenthesizedType */:
18944             case 184 /* TypeOperator */:
18945                 return visitNode(cbNode, node.type);
18946             case 185 /* IndexedAccessType */:
18947                 return visitNode(cbNode, node.objectType) ||
18948                     visitNode(cbNode, node.indexType);
18949             case 186 /* MappedType */:
18950                 return visitNode(cbNode, node.readonlyToken) ||
18951                     visitNode(cbNode, node.typeParameter) ||
18952                     visitNode(cbNode, node.questionToken) ||
18953                     visitNode(cbNode, node.type);
18954             case 187 /* LiteralType */:
18955                 return visitNode(cbNode, node.literal);
18956             case 189 /* ObjectBindingPattern */:
18957             case 190 /* ArrayBindingPattern */:
18958                 return visitNodes(cbNode, cbNodes, node.elements);
18959             case 192 /* ArrayLiteralExpression */:
18960                 return visitNodes(cbNode, cbNodes, node.elements);
18961             case 193 /* ObjectLiteralExpression */:
18962                 return visitNodes(cbNode, cbNodes, node.properties);
18963             case 194 /* PropertyAccessExpression */:
18964                 return visitNode(cbNode, node.expression) ||
18965                     visitNode(cbNode, node.questionDotToken) ||
18966                     visitNode(cbNode, node.name);
18967             case 195 /* ElementAccessExpression */:
18968                 return visitNode(cbNode, node.expression) ||
18969                     visitNode(cbNode, node.questionDotToken) ||
18970                     visitNode(cbNode, node.argumentExpression);
18971             case 196 /* CallExpression */:
18972             case 197 /* NewExpression */:
18973                 return visitNode(cbNode, node.expression) ||
18974                     visitNode(cbNode, node.questionDotToken) ||
18975                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18976                     visitNodes(cbNode, cbNodes, node.arguments);
18977             case 198 /* TaggedTemplateExpression */:
18978                 return visitNode(cbNode, node.tag) ||
18979                     visitNode(cbNode, node.questionDotToken) ||
18980                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18981                     visitNode(cbNode, node.template);
18982             case 199 /* TypeAssertionExpression */:
18983                 return visitNode(cbNode, node.type) ||
18984                     visitNode(cbNode, node.expression);
18985             case 200 /* ParenthesizedExpression */:
18986                 return visitNode(cbNode, node.expression);
18987             case 203 /* DeleteExpression */:
18988                 return visitNode(cbNode, node.expression);
18989             case 204 /* TypeOfExpression */:
18990                 return visitNode(cbNode, node.expression);
18991             case 205 /* VoidExpression */:
18992                 return visitNode(cbNode, node.expression);
18993             case 207 /* PrefixUnaryExpression */:
18994                 return visitNode(cbNode, node.operand);
18995             case 212 /* YieldExpression */:
18996                 return visitNode(cbNode, node.asteriskToken) ||
18997                     visitNode(cbNode, node.expression);
18998             case 206 /* AwaitExpression */:
18999                 return visitNode(cbNode, node.expression);
19000             case 208 /* PostfixUnaryExpression */:
19001                 return visitNode(cbNode, node.operand);
19002             case 209 /* BinaryExpression */:
19003                 return visitNode(cbNode, node.left) ||
19004                     visitNode(cbNode, node.operatorToken) ||
19005                     visitNode(cbNode, node.right);
19006             case 217 /* AsExpression */:
19007                 return visitNode(cbNode, node.expression) ||
19008                     visitNode(cbNode, node.type);
19009             case 218 /* NonNullExpression */:
19010                 return visitNode(cbNode, node.expression);
19011             case 219 /* MetaProperty */:
19012                 return visitNode(cbNode, node.name);
19013             case 210 /* ConditionalExpression */:
19014                 return visitNode(cbNode, node.condition) ||
19015                     visitNode(cbNode, node.questionToken) ||
19016                     visitNode(cbNode, node.whenTrue) ||
19017                     visitNode(cbNode, node.colonToken) ||
19018                     visitNode(cbNode, node.whenFalse);
19019             case 213 /* SpreadElement */:
19020                 return visitNode(cbNode, node.expression);
19021             case 223 /* Block */:
19022             case 250 /* ModuleBlock */:
19023                 return visitNodes(cbNode, cbNodes, node.statements);
19024             case 290 /* SourceFile */:
19025                 return visitNodes(cbNode, cbNodes, node.statements) ||
19026                     visitNode(cbNode, node.endOfFileToken);
19027             case 225 /* VariableStatement */:
19028                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19029                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19030                     visitNode(cbNode, node.declarationList);
19031             case 243 /* VariableDeclarationList */:
19032                 return visitNodes(cbNode, cbNodes, node.declarations);
19033             case 226 /* ExpressionStatement */:
19034                 return visitNode(cbNode, node.expression);
19035             case 227 /* IfStatement */:
19036                 return visitNode(cbNode, node.expression) ||
19037                     visitNode(cbNode, node.thenStatement) ||
19038                     visitNode(cbNode, node.elseStatement);
19039             case 228 /* DoStatement */:
19040                 return visitNode(cbNode, node.statement) ||
19041                     visitNode(cbNode, node.expression);
19042             case 229 /* WhileStatement */:
19043                 return visitNode(cbNode, node.expression) ||
19044                     visitNode(cbNode, node.statement);
19045             case 230 /* ForStatement */:
19046                 return visitNode(cbNode, node.initializer) ||
19047                     visitNode(cbNode, node.condition) ||
19048                     visitNode(cbNode, node.incrementor) ||
19049                     visitNode(cbNode, node.statement);
19050             case 231 /* ForInStatement */:
19051                 return visitNode(cbNode, node.initializer) ||
19052                     visitNode(cbNode, node.expression) ||
19053                     visitNode(cbNode, node.statement);
19054             case 232 /* ForOfStatement */:
19055                 return visitNode(cbNode, node.awaitModifier) ||
19056                     visitNode(cbNode, node.initializer) ||
19057                     visitNode(cbNode, node.expression) ||
19058                     visitNode(cbNode, node.statement);
19059             case 233 /* ContinueStatement */:
19060             case 234 /* BreakStatement */:
19061                 return visitNode(cbNode, node.label);
19062             case 235 /* ReturnStatement */:
19063                 return visitNode(cbNode, node.expression);
19064             case 236 /* WithStatement */:
19065                 return visitNode(cbNode, node.expression) ||
19066                     visitNode(cbNode, node.statement);
19067             case 237 /* SwitchStatement */:
19068                 return visitNode(cbNode, node.expression) ||
19069                     visitNode(cbNode, node.caseBlock);
19070             case 251 /* CaseBlock */:
19071                 return visitNodes(cbNode, cbNodes, node.clauses);
19072             case 277 /* CaseClause */:
19073                 return visitNode(cbNode, node.expression) ||
19074                     visitNodes(cbNode, cbNodes, node.statements);
19075             case 278 /* DefaultClause */:
19076                 return visitNodes(cbNode, cbNodes, node.statements);
19077             case 238 /* LabeledStatement */:
19078                 return visitNode(cbNode, node.label) ||
19079                     visitNode(cbNode, node.statement);
19080             case 239 /* ThrowStatement */:
19081                 return visitNode(cbNode, node.expression);
19082             case 240 /* TryStatement */:
19083                 return visitNode(cbNode, node.tryBlock) ||
19084                     visitNode(cbNode, node.catchClause) ||
19085                     visitNode(cbNode, node.finallyBlock);
19086             case 280 /* CatchClause */:
19087                 return visitNode(cbNode, node.variableDeclaration) ||
19088                     visitNode(cbNode, node.block);
19089             case 157 /* Decorator */:
19090                 return visitNode(cbNode, node.expression);
19091             case 245 /* ClassDeclaration */:
19092             case 214 /* ClassExpression */:
19093                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19094                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19095                     visitNode(cbNode, node.name) ||
19096                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19097                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19098                     visitNodes(cbNode, cbNodes, node.members);
19099             case 246 /* InterfaceDeclaration */:
19100                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19101                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19102                     visitNode(cbNode, node.name) ||
19103                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19104                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19105                     visitNodes(cbNode, cbNodes, node.members);
19106             case 247 /* TypeAliasDeclaration */:
19107                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19108                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19109                     visitNode(cbNode, node.name) ||
19110                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19111                     visitNode(cbNode, node.type);
19112             case 248 /* EnumDeclaration */:
19113                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19114                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19115                     visitNode(cbNode, node.name) ||
19116                     visitNodes(cbNode, cbNodes, node.members);
19117             case 284 /* EnumMember */:
19118                 return visitNode(cbNode, node.name) ||
19119                     visitNode(cbNode, node.initializer);
19120             case 249 /* ModuleDeclaration */:
19121                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19122                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19123                     visitNode(cbNode, node.name) ||
19124                     visitNode(cbNode, node.body);
19125             case 253 /* ImportEqualsDeclaration */:
19126                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19127                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19128                     visitNode(cbNode, node.name) ||
19129                     visitNode(cbNode, node.moduleReference);
19130             case 254 /* ImportDeclaration */:
19131                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19132                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19133                     visitNode(cbNode, node.importClause) ||
19134                     visitNode(cbNode, node.moduleSpecifier);
19135             case 255 /* ImportClause */:
19136                 return visitNode(cbNode, node.name) ||
19137                     visitNode(cbNode, node.namedBindings);
19138             case 252 /* NamespaceExportDeclaration */:
19139                 return visitNode(cbNode, node.name);
19140             case 256 /* NamespaceImport */:
19141                 return visitNode(cbNode, node.name);
19142             case 262 /* NamespaceExport */:
19143                 return visitNode(cbNode, node.name);
19144             case 257 /* NamedImports */:
19145             case 261 /* NamedExports */:
19146                 return visitNodes(cbNode, cbNodes, node.elements);
19147             case 260 /* ExportDeclaration */:
19148                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19149                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19150                     visitNode(cbNode, node.exportClause) ||
19151                     visitNode(cbNode, node.moduleSpecifier);
19152             case 258 /* ImportSpecifier */:
19153             case 263 /* ExportSpecifier */:
19154                 return visitNode(cbNode, node.propertyName) ||
19155                     visitNode(cbNode, node.name);
19156             case 259 /* ExportAssignment */:
19157                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19158                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19159                     visitNode(cbNode, node.expression);
19160             case 211 /* TemplateExpression */:
19161                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19162             case 221 /* TemplateSpan */:
19163                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19164             case 154 /* ComputedPropertyName */:
19165                 return visitNode(cbNode, node.expression);
19166             case 279 /* HeritageClause */:
19167                 return visitNodes(cbNode, cbNodes, node.types);
19168             case 216 /* ExpressionWithTypeArguments */:
19169                 return visitNode(cbNode, node.expression) ||
19170                     visitNodes(cbNode, cbNodes, node.typeArguments);
19171             case 265 /* ExternalModuleReference */:
19172                 return visitNode(cbNode, node.expression);
19173             case 264 /* MissingDeclaration */:
19174                 return visitNodes(cbNode, cbNodes, node.decorators);
19175             case 327 /* CommaListExpression */:
19176                 return visitNodes(cbNode, cbNodes, node.elements);
19177             case 266 /* JsxElement */:
19178                 return visitNode(cbNode, node.openingElement) ||
19179                     visitNodes(cbNode, cbNodes, node.children) ||
19180                     visitNode(cbNode, node.closingElement);
19181             case 270 /* JsxFragment */:
19182                 return visitNode(cbNode, node.openingFragment) ||
19183                     visitNodes(cbNode, cbNodes, node.children) ||
19184                     visitNode(cbNode, node.closingFragment);
19185             case 267 /* JsxSelfClosingElement */:
19186             case 268 /* JsxOpeningElement */:
19187                 return visitNode(cbNode, node.tagName) ||
19188                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19189                     visitNode(cbNode, node.attributes);
19190             case 274 /* JsxAttributes */:
19191                 return visitNodes(cbNode, cbNodes, node.properties);
19192             case 273 /* JsxAttribute */:
19193                 return visitNode(cbNode, node.name) ||
19194                     visitNode(cbNode, node.initializer);
19195             case 275 /* JsxSpreadAttribute */:
19196                 return visitNode(cbNode, node.expression);
19197             case 276 /* JsxExpression */:
19198                 return visitNode(cbNode, node.dotDotDotToken) ||
19199                     visitNode(cbNode, node.expression);
19200             case 269 /* JsxClosingElement */:
19201                 return visitNode(cbNode, node.tagName);
19202             case 176 /* OptionalType */:
19203             case 177 /* RestType */:
19204             case 294 /* JSDocTypeExpression */:
19205             case 298 /* JSDocNonNullableType */:
19206             case 297 /* JSDocNullableType */:
19207             case 299 /* JSDocOptionalType */:
19208             case 301 /* JSDocVariadicType */:
19209                 return visitNode(cbNode, node.type);
19210             case 300 /* JSDocFunctionType */:
19211                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19212                     visitNode(cbNode, node.type);
19213             case 303 /* JSDocComment */:
19214                 return visitNodes(cbNode, cbNodes, node.tags);
19215             case 317 /* JSDocParameterTag */:
19216             case 323 /* JSDocPropertyTag */:
19217                 return visitNode(cbNode, node.tagName) ||
19218                     (node.isNameFirst
19219                         ? visitNode(cbNode, node.name) ||
19220                             visitNode(cbNode, node.typeExpression)
19221                         : visitNode(cbNode, node.typeExpression) ||
19222                             visitNode(cbNode, node.name));
19223             case 309 /* JSDocAuthorTag */:
19224                 return visitNode(cbNode, node.tagName);
19225             case 308 /* JSDocImplementsTag */:
19226                 return visitNode(cbNode, node.tagName) ||
19227                     visitNode(cbNode, node.class);
19228             case 307 /* JSDocAugmentsTag */:
19229                 return visitNode(cbNode, node.tagName) ||
19230                     visitNode(cbNode, node.class);
19231             case 321 /* JSDocTemplateTag */:
19232                 return visitNode(cbNode, node.tagName) ||
19233                     visitNode(cbNode, node.constraint) ||
19234                     visitNodes(cbNode, cbNodes, node.typeParameters);
19235             case 322 /* JSDocTypedefTag */:
19236                 return visitNode(cbNode, node.tagName) ||
19237                     (node.typeExpression &&
19238                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19239                         ? visitNode(cbNode, node.typeExpression) ||
19240                             visitNode(cbNode, node.fullName)
19241                         : visitNode(cbNode, node.fullName) ||
19242                             visitNode(cbNode, node.typeExpression));
19243             case 315 /* JSDocCallbackTag */:
19244                 return visitNode(cbNode, node.tagName) ||
19245                     visitNode(cbNode, node.fullName) ||
19246                     visitNode(cbNode, node.typeExpression);
19247             case 318 /* JSDocReturnTag */:
19248             case 320 /* JSDocTypeTag */:
19249             case 319 /* JSDocThisTag */:
19250             case 316 /* JSDocEnumTag */:
19251                 return visitNode(cbNode, node.tagName) ||
19252                     visitNode(cbNode, node.typeExpression);
19253             case 305 /* JSDocSignature */:
19254                 return ts.forEach(node.typeParameters, cbNode) ||
19255                     ts.forEach(node.parameters, cbNode) ||
19256                     visitNode(cbNode, node.type);
19257             case 304 /* JSDocTypeLiteral */:
19258                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19259             case 306 /* JSDocTag */:
19260             case 310 /* JSDocClassTag */:
19261             case 311 /* JSDocPublicTag */:
19262             case 312 /* JSDocPrivateTag */:
19263             case 313 /* JSDocProtectedTag */:
19264             case 314 /* JSDocReadonlyTag */:
19265                 return visitNode(cbNode, node.tagName);
19266             case 326 /* PartiallyEmittedExpression */:
19267                 return visitNode(cbNode, node.expression);
19268         }
19269     }
19270     ts.forEachChild = forEachChild;
19271     /** @internal */
19272     /**
19273      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19274      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19275      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19276      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19277      *
19278      * @param node a given node to visit its children
19279      * @param cbNode a callback to be invoked for all child nodes
19280      * @param cbNodes a callback to be invoked for embedded array
19281      *
19282      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19283      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19284      */
19285     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19286         var stack = [rootNode];
19287         while (stack.length) {
19288             var parent = stack.pop();
19289             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19290             if (res) {
19291                 return res;
19292             }
19293         }
19294         return;
19295         function gatherPossibleChildren(node) {
19296             var children = [];
19297             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19298             return children;
19299             function addWorkItem(n) {
19300                 children.unshift(n);
19301             }
19302         }
19303         function visitAllPossibleChildren(parent, children) {
19304             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19305                 var child = children_1[_i];
19306                 if (ts.isArray(child)) {
19307                     if (cbNodes) {
19308                         var res = cbNodes(child, parent);
19309                         if (res) {
19310                             if (res === "skip")
19311                                 continue;
19312                             return res;
19313                         }
19314                     }
19315                     for (var i = child.length - 1; i >= 0; i--) {
19316                         var realChild = child[i];
19317                         var res = cbNode(realChild, parent);
19318                         if (res) {
19319                             if (res === "skip")
19320                                 continue;
19321                             return res;
19322                         }
19323                         stack.push(realChild);
19324                     }
19325                 }
19326                 else {
19327                     stack.push(child);
19328                     var res = cbNode(child, parent);
19329                     if (res) {
19330                         if (res === "skip")
19331                             continue;
19332                         return res;
19333                     }
19334                 }
19335             }
19336         }
19337     }
19338     ts.forEachChildRecursively = forEachChildRecursively;
19339     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19340         if (setParentNodes === void 0) { setParentNodes = false; }
19341         ts.performance.mark("beforeParse");
19342         var result;
19343         ts.perfLogger.logStartParseSourceFile(fileName);
19344         if (languageVersion === 100 /* JSON */) {
19345             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19346         }
19347         else {
19348             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19349         }
19350         ts.perfLogger.logStopParseSourceFile();
19351         ts.performance.mark("afterParse");
19352         ts.performance.measure("Parse", "beforeParse", "afterParse");
19353         return result;
19354     }
19355     ts.createSourceFile = createSourceFile;
19356     function parseIsolatedEntityName(text, languageVersion) {
19357         return Parser.parseIsolatedEntityName(text, languageVersion);
19358     }
19359     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19360     /**
19361      * Parse json text into SyntaxTree and return node and parse errors if any
19362      * @param fileName
19363      * @param sourceText
19364      */
19365     function parseJsonText(fileName, sourceText) {
19366         return Parser.parseJsonText(fileName, sourceText);
19367     }
19368     ts.parseJsonText = parseJsonText;
19369     // See also `isExternalOrCommonJsModule` in utilities.ts
19370     function isExternalModule(file) {
19371         return file.externalModuleIndicator !== undefined;
19372     }
19373     ts.isExternalModule = isExternalModule;
19374     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19375     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19376     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19377     // this file as possible.
19378     //
19379     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19380     // from this SourceFile that are being held onto may change as a result (including
19381     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19382     // be used once 'update' is called on it.
19383     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19384         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19385         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19386         // 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.
19387         // We will manually port the flag to the new source file.
19388         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19389         return newSourceFile;
19390     }
19391     ts.updateSourceFile = updateSourceFile;
19392     /* @internal */
19393     function parseIsolatedJSDocComment(content, start, length) {
19394         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19395         if (result && result.jsDoc) {
19396             // because the jsDocComment was parsed out of the source file, it might
19397             // not be covered by the fixupParentReferences.
19398             Parser.fixupParentReferences(result.jsDoc);
19399         }
19400         return result;
19401     }
19402     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19403     /* @internal */
19404     // Exposed only for testing.
19405     function parseJSDocTypeExpressionForTests(content, start, length) {
19406         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19407     }
19408     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19409     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19410     // parser instances can actually be expensive enough to impact us on projects with many source
19411     // files.
19412     var Parser;
19413     (function (Parser) {
19414         // Share a single scanner across all calls to parse a source file.  This helps speed things
19415         // up by avoiding the cost of creating/compiling scanners over and over again.
19416         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19417         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19418         // capture constructors in 'initializeState' to avoid null checks
19419         var NodeConstructor;
19420         var TokenConstructor;
19421         var IdentifierConstructor;
19422         var PrivateIdentifierConstructor;
19423         var SourceFileConstructor;
19424         var sourceFile;
19425         var parseDiagnostics;
19426         var syntaxCursor;
19427         var currentToken;
19428         var sourceText;
19429         var nodeCount;
19430         var identifiers;
19431         var privateIdentifiers;
19432         var identifierCount;
19433         var parsingContext;
19434         var notParenthesizedArrow;
19435         // Flags that dictate what parsing context we're in.  For example:
19436         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19437         // that some tokens that would be considered identifiers may be considered keywords.
19438         //
19439         // When adding more parser context flags, consider which is the more common case that the
19440         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19441         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19442         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19443         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19444         // all nodes would need extra state on them to store this info.
19445         //
19446         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19447         // grammar specification.
19448         //
19449         // An important thing about these context concepts.  By default they are effectively inherited
19450         // while parsing through every grammar production.  i.e. if you don't change them, then when
19451         // you parse a sub-production, it will have the same context values as the parent production.
19452         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19453         // and how nearly all of them pass along the 'in' and 'yield' context values:
19454         //
19455         // EqualityExpression[In, Yield] :
19456         //      RelationalExpression[?In, ?Yield]
19457         //      EqualityExpression[?In, ?Yield] == 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         //
19462         // Where you have to be careful is then understanding what the points are in the grammar
19463         // where the values are *not* passed along.  For example:
19464         //
19465         // SingleNameBinding[Yield,GeneratorParameter]
19466         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19467         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19468         //
19469         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19470         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19471         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19472         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19473         // should leave the 'yield' context flag alone.
19474         //
19475         // Getting this all correct is tricky and requires careful reading of the grammar to
19476         // understand when these values should be changed versus when they should be inherited.
19477         //
19478         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19479         // parsing.  These context flags are naturally stored and restored through normal recursive
19480         // descent parsing and unwinding.
19481         var contextFlags;
19482         // Whether or not we've had a parse error since creating the last AST node.  If we have
19483         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19484         // can be broken down into three categories:
19485         //
19486         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19487         //    character that was completely not understood.
19488         //
19489         // 2) A token was expected, but was not present.  This type of error is commonly produced
19490         //    by the 'parseExpected' function.
19491         //
19492         // 3) A token was present that no parsing function was able to consume.  This type of error
19493         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19494         //    decides to skip the token.
19495         //
19496         // In all of these cases, we want to mark the next node as having had an error before it.
19497         // With this mark, we can know in incremental settings if this node can be reused, or if
19498         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19499         // node.  in that event we would then not produce the same errors as we did before, causing
19500         // significant confusion problems.
19501         //
19502         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19503         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19504         // this value attached, and then this value will be set back to 'false'.  If we decide to
19505         // rewind, we must get back to the same value we had prior to the lookahead.
19506         //
19507         // Note: any errors at the end of the file that do not precede a regular node, should get
19508         // attached to the EOF token.
19509         var parseErrorBeforeNextFinishedNode = false;
19510         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19511             if (setParentNodes === void 0) { setParentNodes = false; }
19512             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19513             if (scriptKind === 6 /* JSON */) {
19514                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19515                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19516                 result_2.referencedFiles = ts.emptyArray;
19517                 result_2.typeReferenceDirectives = ts.emptyArray;
19518                 result_2.libReferenceDirectives = ts.emptyArray;
19519                 result_2.amdDependencies = ts.emptyArray;
19520                 result_2.hasNoDefaultLib = false;
19521                 result_2.pragmas = ts.emptyMap;
19522                 return result_2;
19523             }
19524             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19525             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19526             clearState();
19527             return result;
19528         }
19529         Parser.parseSourceFile = parseSourceFile;
19530         function parseIsolatedEntityName(content, languageVersion) {
19531             // Choice of `isDeclarationFile` should be arbitrary
19532             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19533             // Prime the scanner.
19534             nextToken();
19535             var entityName = parseEntityName(/*allowReservedWords*/ true);
19536             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19537             clearState();
19538             return isInvalid ? entityName : undefined;
19539         }
19540         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19541         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19542             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19543             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19544             // Set source file so that errors will be reported with this file name
19545             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19546             sourceFile.flags = contextFlags;
19547             // Prime the scanner.
19548             nextToken();
19549             var pos = getNodePos();
19550             if (token() === 1 /* EndOfFileToken */) {
19551                 sourceFile.statements = createNodeArray([], pos, pos);
19552                 sourceFile.endOfFileToken = parseTokenNode();
19553             }
19554             else {
19555                 var statement = createNode(226 /* ExpressionStatement */);
19556                 switch (token()) {
19557                     case 22 /* OpenBracketToken */:
19558                         statement.expression = parseArrayLiteralExpression();
19559                         break;
19560                     case 106 /* TrueKeyword */:
19561                     case 91 /* FalseKeyword */:
19562                     case 100 /* NullKeyword */:
19563                         statement.expression = parseTokenNode();
19564                         break;
19565                     case 40 /* MinusToken */:
19566                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19567                             statement.expression = parsePrefixUnaryExpression();
19568                         }
19569                         else {
19570                             statement.expression = parseObjectLiteralExpression();
19571                         }
19572                         break;
19573                     case 8 /* NumericLiteral */:
19574                     case 10 /* StringLiteral */:
19575                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19576                             statement.expression = parseLiteralNode();
19577                             break;
19578                         }
19579                     // falls through
19580                     default:
19581                         statement.expression = parseObjectLiteralExpression();
19582                         break;
19583                 }
19584                 finishNode(statement);
19585                 sourceFile.statements = createNodeArray([statement], pos);
19586                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19587             }
19588             if (setParentNodes) {
19589                 fixupParentReferences(sourceFile);
19590             }
19591             sourceFile.nodeCount = nodeCount;
19592             sourceFile.identifierCount = identifierCount;
19593             sourceFile.identifiers = identifiers;
19594             sourceFile.parseDiagnostics = parseDiagnostics;
19595             var result = sourceFile;
19596             clearState();
19597             return result;
19598         }
19599         Parser.parseJsonText = parseJsonText;
19600         function getLanguageVariant(scriptKind) {
19601             // .tsx and .jsx files are treated as jsx language variant.
19602             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19603         }
19604         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19605             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19606             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19607             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19608             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19609             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19610             sourceText = _sourceText;
19611             syntaxCursor = _syntaxCursor;
19612             parseDiagnostics = [];
19613             parsingContext = 0;
19614             identifiers = ts.createMap();
19615             privateIdentifiers = ts.createMap();
19616             identifierCount = 0;
19617             nodeCount = 0;
19618             switch (scriptKind) {
19619                 case 1 /* JS */:
19620                 case 2 /* JSX */:
19621                     contextFlags = 131072 /* JavaScriptFile */;
19622                     break;
19623                 case 6 /* JSON */:
19624                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19625                     break;
19626                 default:
19627                     contextFlags = 0 /* None */;
19628                     break;
19629             }
19630             parseErrorBeforeNextFinishedNode = false;
19631             // Initialize and prime the scanner before parsing the source elements.
19632             scanner.setText(sourceText);
19633             scanner.setOnError(scanError);
19634             scanner.setScriptTarget(languageVersion);
19635             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19636         }
19637         function clearState() {
19638             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19639             scanner.clearCommentDirectives();
19640             scanner.setText("");
19641             scanner.setOnError(undefined);
19642             // Clear any data.  We don't want to accidentally hold onto it for too long.
19643             parseDiagnostics = undefined;
19644             sourceFile = undefined;
19645             identifiers = undefined;
19646             syntaxCursor = undefined;
19647             sourceText = undefined;
19648             notParenthesizedArrow = undefined;
19649         }
19650         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19651             var isDeclarationFile = isDeclarationFileName(fileName);
19652             if (isDeclarationFile) {
19653                 contextFlags |= 8388608 /* Ambient */;
19654             }
19655             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19656             sourceFile.flags = contextFlags;
19657             // Prime the scanner.
19658             nextToken();
19659             // 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
19660             processCommentPragmas(sourceFile, sourceText);
19661             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19662             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19663             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19664             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19665             setExternalModuleIndicator(sourceFile);
19666             sourceFile.commentDirectives = scanner.getCommentDirectives();
19667             sourceFile.nodeCount = nodeCount;
19668             sourceFile.identifierCount = identifierCount;
19669             sourceFile.identifiers = identifiers;
19670             sourceFile.parseDiagnostics = parseDiagnostics;
19671             if (setParentNodes) {
19672                 fixupParentReferences(sourceFile);
19673             }
19674             return sourceFile;
19675             function reportPragmaDiagnostic(pos, end, diagnostic) {
19676                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19677             }
19678         }
19679         function addJSDocComment(node) {
19680             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19681             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19682             if (jsDoc.length)
19683                 node.jsDoc = jsDoc;
19684             return node;
19685         }
19686         function fixupParentReferences(rootNode) {
19687             // normally parent references are set during binding. However, for clients that only need
19688             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19689             // overhead.  This functions allows us to set all the parents, without all the expense of
19690             // binding.
19691             forEachChildRecursively(rootNode, bindParentToChild);
19692             function bindParentToChild(child, parent) {
19693                 child.parent = parent;
19694                 if (ts.hasJSDocNodes(child)) {
19695                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19696                         var doc = _a[_i];
19697                         bindParentToChild(doc, child);
19698                         forEachChildRecursively(doc, bindParentToChild);
19699                     }
19700                 }
19701             }
19702         }
19703         Parser.fixupParentReferences = fixupParentReferences;
19704         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19705             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19706             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19707             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19708             nodeCount++;
19709             sourceFile.text = sourceText;
19710             sourceFile.bindDiagnostics = [];
19711             sourceFile.bindSuggestionDiagnostics = undefined;
19712             sourceFile.languageVersion = languageVersion;
19713             sourceFile.fileName = ts.normalizePath(fileName);
19714             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19715             sourceFile.isDeclarationFile = isDeclarationFile;
19716             sourceFile.scriptKind = scriptKind;
19717             return sourceFile;
19718         }
19719         function setContextFlag(val, flag) {
19720             if (val) {
19721                 contextFlags |= flag;
19722             }
19723             else {
19724                 contextFlags &= ~flag;
19725             }
19726         }
19727         function setDisallowInContext(val) {
19728             setContextFlag(val, 4096 /* DisallowInContext */);
19729         }
19730         function setYieldContext(val) {
19731             setContextFlag(val, 8192 /* YieldContext */);
19732         }
19733         function setDecoratorContext(val) {
19734             setContextFlag(val, 16384 /* DecoratorContext */);
19735         }
19736         function setAwaitContext(val) {
19737             setContextFlag(val, 32768 /* AwaitContext */);
19738         }
19739         function doOutsideOfContext(context, func) {
19740             // contextFlagsToClear will contain only the context flags that are
19741             // currently set that we need to temporarily clear
19742             // We don't just blindly reset to the previous flags to ensure
19743             // that we do not mutate cached flags for the incremental
19744             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19745             // HasAggregatedChildData).
19746             var contextFlagsToClear = context & contextFlags;
19747             if (contextFlagsToClear) {
19748                 // clear the requested context flags
19749                 setContextFlag(/*val*/ false, contextFlagsToClear);
19750                 var result = func();
19751                 // restore the context flags we just cleared
19752                 setContextFlag(/*val*/ true, contextFlagsToClear);
19753                 return result;
19754             }
19755             // no need to do anything special as we are not in any of the requested contexts
19756             return func();
19757         }
19758         function doInsideOfContext(context, func) {
19759             // contextFlagsToSet will contain only the context flags that
19760             // are not currently set that we need to temporarily enable.
19761             // We don't just blindly reset to the previous flags to ensure
19762             // that we do not mutate cached flags for the incremental
19763             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19764             // HasAggregatedChildData).
19765             var contextFlagsToSet = context & ~contextFlags;
19766             if (contextFlagsToSet) {
19767                 // set the requested context flags
19768                 setContextFlag(/*val*/ true, contextFlagsToSet);
19769                 var result = func();
19770                 // reset the context flags we just set
19771                 setContextFlag(/*val*/ false, contextFlagsToSet);
19772                 return result;
19773             }
19774             // no need to do anything special as we are already in all of the requested contexts
19775             return func();
19776         }
19777         function allowInAnd(func) {
19778             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19779         }
19780         function disallowInAnd(func) {
19781             return doInsideOfContext(4096 /* DisallowInContext */, func);
19782         }
19783         function doInYieldContext(func) {
19784             return doInsideOfContext(8192 /* YieldContext */, func);
19785         }
19786         function doInDecoratorContext(func) {
19787             return doInsideOfContext(16384 /* DecoratorContext */, func);
19788         }
19789         function doInAwaitContext(func) {
19790             return doInsideOfContext(32768 /* AwaitContext */, func);
19791         }
19792         function doOutsideOfAwaitContext(func) {
19793             return doOutsideOfContext(32768 /* AwaitContext */, func);
19794         }
19795         function doInYieldAndAwaitContext(func) {
19796             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19797         }
19798         function doOutsideOfYieldAndAwaitContext(func) {
19799             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19800         }
19801         function inContext(flags) {
19802             return (contextFlags & flags) !== 0;
19803         }
19804         function inYieldContext() {
19805             return inContext(8192 /* YieldContext */);
19806         }
19807         function inDisallowInContext() {
19808             return inContext(4096 /* DisallowInContext */);
19809         }
19810         function inDecoratorContext() {
19811             return inContext(16384 /* DecoratorContext */);
19812         }
19813         function inAwaitContext() {
19814             return inContext(32768 /* AwaitContext */);
19815         }
19816         function parseErrorAtCurrentToken(message, arg0) {
19817             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19818         }
19819         function parseErrorAtPosition(start, length, message, arg0) {
19820             // Don't report another error if it would just be at the same position as the last error.
19821             var lastError = ts.lastOrUndefined(parseDiagnostics);
19822             if (!lastError || start !== lastError.start) {
19823                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19824             }
19825             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19826             // node we finish so that it can't be reused incrementally.
19827             parseErrorBeforeNextFinishedNode = true;
19828         }
19829         function parseErrorAt(start, end, message, arg0) {
19830             parseErrorAtPosition(start, end - start, message, arg0);
19831         }
19832         function parseErrorAtRange(range, message, arg0) {
19833             parseErrorAt(range.pos, range.end, message, arg0);
19834         }
19835         function scanError(message, length) {
19836             parseErrorAtPosition(scanner.getTextPos(), length, message);
19837         }
19838         function getNodePos() {
19839             return scanner.getStartPos();
19840         }
19841         // Use this function to access the current token instead of reading the currentToken
19842         // variable. Since function results aren't narrowed in control flow analysis, this ensures
19843         // that the type checker doesn't make wrong assumptions about the type of the current
19844         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
19845         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
19846         // there is no performance penalty.
19847         function token() {
19848             return currentToken;
19849         }
19850         function nextTokenWithoutCheck() {
19851             return currentToken = scanner.scan();
19852         }
19853         function nextToken() {
19854             // if the keyword had an escape
19855             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
19856                 // issue a parse error for the escape
19857                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
19858             }
19859             return nextTokenWithoutCheck();
19860         }
19861         function nextTokenJSDoc() {
19862             return currentToken = scanner.scanJsDocToken();
19863         }
19864         function reScanGreaterToken() {
19865             return currentToken = scanner.reScanGreaterToken();
19866         }
19867         function reScanSlashToken() {
19868             return currentToken = scanner.reScanSlashToken();
19869         }
19870         function reScanTemplateToken(isTaggedTemplate) {
19871             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
19872         }
19873         function reScanTemplateHeadOrNoSubstitutionTemplate() {
19874             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
19875         }
19876         function reScanLessThanToken() {
19877             return currentToken = scanner.reScanLessThanToken();
19878         }
19879         function scanJsxIdentifier() {
19880             return currentToken = scanner.scanJsxIdentifier();
19881         }
19882         function scanJsxText() {
19883             return currentToken = scanner.scanJsxToken();
19884         }
19885         function scanJsxAttributeValue() {
19886             return currentToken = scanner.scanJsxAttributeValue();
19887         }
19888         function speculationHelper(callback, isLookAhead) {
19889             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
19890             // caller asked us to always reset our state).
19891             var saveToken = currentToken;
19892             var saveParseDiagnosticsLength = parseDiagnostics.length;
19893             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
19894             // Note: it is not actually necessary to save/restore the context flags here.  That's
19895             // because the saving/restoring of these flags happens naturally through the recursive
19896             // descent nature of our parser.  However, we still store this here just so we can
19897             // assert that invariant holds.
19898             var saveContextFlags = contextFlags;
19899             // If we're only looking ahead, then tell the scanner to only lookahead as well.
19900             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
19901             // same.
19902             var result = isLookAhead
19903                 ? scanner.lookAhead(callback)
19904                 : scanner.tryScan(callback);
19905             ts.Debug.assert(saveContextFlags === contextFlags);
19906             // If our callback returned something 'falsy' or we're just looking ahead,
19907             // then unconditionally restore us to where we were.
19908             if (!result || isLookAhead) {
19909                 currentToken = saveToken;
19910                 parseDiagnostics.length = saveParseDiagnosticsLength;
19911                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
19912             }
19913             return result;
19914         }
19915         /** Invokes the provided callback then unconditionally restores the parser to the state it
19916          * was in immediately prior to invoking the callback.  The result of invoking the callback
19917          * is returned from this function.
19918          */
19919         function lookAhead(callback) {
19920             return speculationHelper(callback, /*isLookAhead*/ true);
19921         }
19922         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
19923          * the parser to the state it was in immediately prior to invoking the callback.  If the
19924          * callback returns something truthy, then the parser state is not rolled back.  The result
19925          * of invoking the callback is returned from this function.
19926          */
19927         function tryParse(callback) {
19928             return speculationHelper(callback, /*isLookAhead*/ false);
19929         }
19930         // Ignore strict mode flag because we will report an error in type checker instead.
19931         function isIdentifier() {
19932             if (token() === 75 /* Identifier */) {
19933                 return true;
19934             }
19935             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
19936             // considered a keyword and is not an identifier.
19937             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
19938                 return false;
19939             }
19940             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
19941             // considered a keyword and is not an identifier.
19942             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
19943                 return false;
19944             }
19945             return token() > 112 /* LastReservedWord */;
19946         }
19947         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
19948             if (shouldAdvance === void 0) { shouldAdvance = true; }
19949             if (token() === kind) {
19950                 if (shouldAdvance) {
19951                     nextToken();
19952                 }
19953                 return true;
19954             }
19955             // Report specific message if provided with one.  Otherwise, report generic fallback message.
19956             if (diagnosticMessage) {
19957                 parseErrorAtCurrentToken(diagnosticMessage);
19958             }
19959             else {
19960                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19961             }
19962             return false;
19963         }
19964         function parseExpectedJSDoc(kind) {
19965             if (token() === kind) {
19966                 nextTokenJSDoc();
19967                 return true;
19968             }
19969             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19970             return false;
19971         }
19972         function parseOptional(t) {
19973             if (token() === t) {
19974                 nextToken();
19975                 return true;
19976             }
19977             return false;
19978         }
19979         function parseOptionalToken(t) {
19980             if (token() === t) {
19981                 return parseTokenNode();
19982             }
19983             return undefined;
19984         }
19985         function parseOptionalTokenJSDoc(t) {
19986             if (token() === t) {
19987                 return parseTokenNodeJSDoc();
19988             }
19989             return undefined;
19990         }
19991         function parseExpectedToken(t, diagnosticMessage, arg0) {
19992             return parseOptionalToken(t) ||
19993                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
19994         }
19995         function parseExpectedTokenJSDoc(t) {
19996             return parseOptionalTokenJSDoc(t) ||
19997                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
19998         }
19999         function parseTokenNode() {
20000             var node = createNode(token());
20001             nextToken();
20002             return finishNode(node);
20003         }
20004         function parseTokenNodeJSDoc() {
20005             var node = createNode(token());
20006             nextTokenJSDoc();
20007             return finishNode(node);
20008         }
20009         function canParseSemicolon() {
20010             // If there's a real semicolon, then we can always parse it out.
20011             if (token() === 26 /* SemicolonToken */) {
20012                 return true;
20013             }
20014             // We can parse out an optional semicolon in ASI cases in the following cases.
20015             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20016         }
20017         function parseSemicolon() {
20018             if (canParseSemicolon()) {
20019                 if (token() === 26 /* SemicolonToken */) {
20020                     // consume the semicolon if it was explicitly provided.
20021                     nextToken();
20022                 }
20023                 return true;
20024             }
20025             else {
20026                 return parseExpected(26 /* SemicolonToken */);
20027             }
20028         }
20029         function createNode(kind, pos) {
20030             nodeCount++;
20031             var p = pos >= 0 ? pos : scanner.getStartPos();
20032             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20033                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20034                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20035                         new TokenConstructor(kind, p, p);
20036         }
20037         function createNodeWithJSDoc(kind, pos) {
20038             var node = createNode(kind, pos);
20039             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20040                 addJSDocComment(node);
20041             }
20042             return node;
20043         }
20044         function createNodeArray(elements, pos, end) {
20045             // Since the element list of a node array is typically created by starting with an empty array and
20046             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20047             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20048             var length = elements.length;
20049             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20050             array.pos = pos;
20051             array.end = end === undefined ? scanner.getStartPos() : end;
20052             return array;
20053         }
20054         function finishNode(node, end) {
20055             node.end = end === undefined ? scanner.getStartPos() : end;
20056             if (contextFlags) {
20057                 node.flags |= contextFlags;
20058             }
20059             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20060             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20061             // flag so that we don't mark any subsequent nodes.
20062             if (parseErrorBeforeNextFinishedNode) {
20063                 parseErrorBeforeNextFinishedNode = false;
20064                 node.flags |= 65536 /* ThisNodeHasError */;
20065             }
20066             return node;
20067         }
20068         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20069             if (reportAtCurrentPosition) {
20070                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20071             }
20072             else if (diagnosticMessage) {
20073                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20074             }
20075             var result = createNode(kind);
20076             if (kind === 75 /* Identifier */) {
20077                 result.escapedText = "";
20078             }
20079             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20080                 result.text = "";
20081             }
20082             return finishNode(result);
20083         }
20084         function internIdentifier(text) {
20085             var identifier = identifiers.get(text);
20086             if (identifier === undefined) {
20087                 identifiers.set(text, identifier = text);
20088             }
20089             return identifier;
20090         }
20091         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20092         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20093         // each identifier in order to reduce memory consumption.
20094         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20095             identifierCount++;
20096             if (isIdentifier) {
20097                 var node = createNode(75 /* Identifier */);
20098                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20099                 if (token() !== 75 /* Identifier */) {
20100                     node.originalKeywordKind = token();
20101                 }
20102                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20103                 nextTokenWithoutCheck();
20104                 return finishNode(node);
20105             }
20106             if (token() === 76 /* PrivateIdentifier */) {
20107                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20108                 return createIdentifier(/*isIdentifier*/ true);
20109             }
20110             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20111             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20112             var isReservedWord = scanner.isReservedWord();
20113             var msgArg = scanner.getTokenText();
20114             var defaultMessage = isReservedWord ?
20115                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20116                 ts.Diagnostics.Identifier_expected;
20117             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20118         }
20119         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20120             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20121         }
20122         function parseIdentifierName(diagnosticMessage) {
20123             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20124         }
20125         function isLiteralPropertyName() {
20126             return ts.tokenIsIdentifierOrKeyword(token()) ||
20127                 token() === 10 /* StringLiteral */ ||
20128                 token() === 8 /* NumericLiteral */;
20129         }
20130         function parsePropertyNameWorker(allowComputedPropertyNames) {
20131             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20132                 var node = parseLiteralNode();
20133                 node.text = internIdentifier(node.text);
20134                 return node;
20135             }
20136             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20137                 return parseComputedPropertyName();
20138             }
20139             if (token() === 76 /* PrivateIdentifier */) {
20140                 return parsePrivateIdentifier();
20141             }
20142             return parseIdentifierName();
20143         }
20144         function parsePropertyName() {
20145             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20146         }
20147         function parseComputedPropertyName() {
20148             // PropertyName [Yield]:
20149             //      LiteralPropertyName
20150             //      ComputedPropertyName[?Yield]
20151             var node = createNode(154 /* ComputedPropertyName */);
20152             parseExpected(22 /* OpenBracketToken */);
20153             // We parse any expression (including a comma expression). But the grammar
20154             // says that only an assignment expression is allowed, so the grammar checker
20155             // will error if it sees a comma expression.
20156             node.expression = allowInAnd(parseExpression);
20157             parseExpected(23 /* CloseBracketToken */);
20158             return finishNode(node);
20159         }
20160         function internPrivateIdentifier(text) {
20161             var privateIdentifier = privateIdentifiers.get(text);
20162             if (privateIdentifier === undefined) {
20163                 privateIdentifiers.set(text, privateIdentifier = text);
20164             }
20165             return privateIdentifier;
20166         }
20167         function parsePrivateIdentifier() {
20168             var node = createNode(76 /* PrivateIdentifier */);
20169             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20170             nextToken();
20171             return finishNode(node);
20172         }
20173         function parseContextualModifier(t) {
20174             return token() === t && tryParse(nextTokenCanFollowModifier);
20175         }
20176         function nextTokenIsOnSameLineAndCanFollowModifier() {
20177             nextToken();
20178             if (scanner.hasPrecedingLineBreak()) {
20179                 return false;
20180             }
20181             return canFollowModifier();
20182         }
20183         function nextTokenCanFollowModifier() {
20184             switch (token()) {
20185                 case 81 /* ConstKeyword */:
20186                     // 'const' is only a modifier if followed by 'enum'.
20187                     return nextToken() === 88 /* EnumKeyword */;
20188                 case 89 /* ExportKeyword */:
20189                     nextToken();
20190                     if (token() === 84 /* DefaultKeyword */) {
20191                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20192                     }
20193                     if (token() === 145 /* TypeKeyword */) {
20194                         return lookAhead(nextTokenCanFollowExportModifier);
20195                     }
20196                     return canFollowExportModifier();
20197                 case 84 /* DefaultKeyword */:
20198                     return nextTokenCanFollowDefaultKeyword();
20199                 case 120 /* StaticKeyword */:
20200                 case 131 /* GetKeyword */:
20201                 case 142 /* SetKeyword */:
20202                     nextToken();
20203                     return canFollowModifier();
20204                 default:
20205                     return nextTokenIsOnSameLineAndCanFollowModifier();
20206             }
20207         }
20208         function canFollowExportModifier() {
20209             return token() !== 41 /* AsteriskToken */
20210                 && token() !== 123 /* AsKeyword */
20211                 && token() !== 18 /* OpenBraceToken */
20212                 && canFollowModifier();
20213         }
20214         function nextTokenCanFollowExportModifier() {
20215             nextToken();
20216             return canFollowExportModifier();
20217         }
20218         function parseAnyContextualModifier() {
20219             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20220         }
20221         function canFollowModifier() {
20222             return token() === 22 /* OpenBracketToken */
20223                 || token() === 18 /* OpenBraceToken */
20224                 || token() === 41 /* AsteriskToken */
20225                 || token() === 25 /* DotDotDotToken */
20226                 || isLiteralPropertyName();
20227         }
20228         function nextTokenCanFollowDefaultKeyword() {
20229             nextToken();
20230             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20231                 token() === 114 /* InterfaceKeyword */ ||
20232                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20233                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20234         }
20235         // True if positioned at the start of a list element
20236         function isListElement(parsingContext, inErrorRecovery) {
20237             var node = currentNode(parsingContext);
20238             if (node) {
20239                 return true;
20240             }
20241             switch (parsingContext) {
20242                 case 0 /* SourceElements */:
20243                 case 1 /* BlockStatements */:
20244                 case 3 /* SwitchClauseStatements */:
20245                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20246                     // The problem is that ';' can show up in far too many contexts, and if we see one
20247                     // and assume it's a statement, then we may bail out inappropriately from whatever
20248                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20249                     // we really don't want to assume the class is over and we're on a statement in the
20250                     // outer module.  We just want to consume and move on.
20251                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20252                 case 2 /* SwitchClauses */:
20253                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20254                 case 4 /* TypeMembers */:
20255                     return lookAhead(isTypeMemberStart);
20256                 case 5 /* ClassMembers */:
20257                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20258                     // not in error recovery.  If we're in error recovery, we don't want an errant
20259                     // semicolon to be treated as a class member (since they're almost always used
20260                     // for statements.
20261                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20262                 case 6 /* EnumMembers */:
20263                     // Include open bracket computed properties. This technically also lets in indexers,
20264                     // which would be a candidate for improved error reporting.
20265                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20266                 case 12 /* ObjectLiteralMembers */:
20267                     switch (token()) {
20268                         case 22 /* OpenBracketToken */:
20269                         case 41 /* AsteriskToken */:
20270                         case 25 /* DotDotDotToken */:
20271                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20272                             return true;
20273                         default:
20274                             return isLiteralPropertyName();
20275                     }
20276                 case 18 /* RestProperties */:
20277                     return isLiteralPropertyName();
20278                 case 9 /* ObjectBindingElements */:
20279                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20280                 case 7 /* HeritageClauseElement */:
20281                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20282                     // That way we won't consume the body of a class in its heritage clause.
20283                     if (token() === 18 /* OpenBraceToken */) {
20284                         return lookAhead(isValidHeritageClauseObjectLiteral);
20285                     }
20286                     if (!inErrorRecovery) {
20287                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20288                     }
20289                     else {
20290                         // If we're in error recovery we tighten up what we're willing to match.
20291                         // That way we don't treat something like "this" as a valid heritage clause
20292                         // element during recovery.
20293                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20294                     }
20295                 case 8 /* VariableDeclarations */:
20296                     return isIdentifierOrPrivateIdentifierOrPattern();
20297                 case 10 /* ArrayBindingElements */:
20298                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20299                 case 19 /* TypeParameters */:
20300                     return isIdentifier();
20301                 case 15 /* ArrayLiteralMembers */:
20302                     switch (token()) {
20303                         case 27 /* CommaToken */:
20304                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20305                             return true;
20306                     }
20307                 // falls through
20308                 case 11 /* ArgumentExpressions */:
20309                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20310                 case 16 /* Parameters */:
20311                     return isStartOfParameter(/*isJSDocParameter*/ false);
20312                 case 17 /* JSDocParameters */:
20313                     return isStartOfParameter(/*isJSDocParameter*/ true);
20314                 case 20 /* TypeArguments */:
20315                 case 21 /* TupleElementTypes */:
20316                     return token() === 27 /* CommaToken */ || isStartOfType();
20317                 case 22 /* HeritageClauses */:
20318                     return isHeritageClause();
20319                 case 23 /* ImportOrExportSpecifiers */:
20320                     return ts.tokenIsIdentifierOrKeyword(token());
20321                 case 13 /* JsxAttributes */:
20322                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20323                 case 14 /* JsxChildren */:
20324                     return true;
20325             }
20326             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20327         }
20328         function isValidHeritageClauseObjectLiteral() {
20329             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20330             if (nextToken() === 19 /* CloseBraceToken */) {
20331                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20332                 // the class body) if we have:
20333                 //
20334                 //      extends {} {
20335                 //      extends {},
20336                 //      extends {} extends
20337                 //      extends {} implements
20338                 var next = nextToken();
20339                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20340             }
20341             return true;
20342         }
20343         function nextTokenIsIdentifier() {
20344             nextToken();
20345             return isIdentifier();
20346         }
20347         function nextTokenIsIdentifierOrKeyword() {
20348             nextToken();
20349             return ts.tokenIsIdentifierOrKeyword(token());
20350         }
20351         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20352             nextToken();
20353             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20354         }
20355         function isHeritageClauseExtendsOrImplementsKeyword() {
20356             if (token() === 113 /* ImplementsKeyword */ ||
20357                 token() === 90 /* ExtendsKeyword */) {
20358                 return lookAhead(nextTokenIsStartOfExpression);
20359             }
20360             return false;
20361         }
20362         function nextTokenIsStartOfExpression() {
20363             nextToken();
20364             return isStartOfExpression();
20365         }
20366         function nextTokenIsStartOfType() {
20367             nextToken();
20368             return isStartOfType();
20369         }
20370         // True if positioned at a list terminator
20371         function isListTerminator(kind) {
20372             if (token() === 1 /* EndOfFileToken */) {
20373                 // Being at the end of the file ends all lists.
20374                 return true;
20375             }
20376             switch (kind) {
20377                 case 1 /* BlockStatements */:
20378                 case 2 /* SwitchClauses */:
20379                 case 4 /* TypeMembers */:
20380                 case 5 /* ClassMembers */:
20381                 case 6 /* EnumMembers */:
20382                 case 12 /* ObjectLiteralMembers */:
20383                 case 9 /* ObjectBindingElements */:
20384                 case 23 /* ImportOrExportSpecifiers */:
20385                     return token() === 19 /* CloseBraceToken */;
20386                 case 3 /* SwitchClauseStatements */:
20387                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20388                 case 7 /* HeritageClauseElement */:
20389                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20390                 case 8 /* VariableDeclarations */:
20391                     return isVariableDeclaratorListTerminator();
20392                 case 19 /* TypeParameters */:
20393                     // Tokens other than '>' are here for better error recovery
20394                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20395                 case 11 /* ArgumentExpressions */:
20396                     // Tokens other than ')' are here for better error recovery
20397                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20398                 case 15 /* ArrayLiteralMembers */:
20399                 case 21 /* TupleElementTypes */:
20400                 case 10 /* ArrayBindingElements */:
20401                     return token() === 23 /* CloseBracketToken */;
20402                 case 17 /* JSDocParameters */:
20403                 case 16 /* Parameters */:
20404                 case 18 /* RestProperties */:
20405                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20406                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20407                 case 20 /* TypeArguments */:
20408                     // All other tokens should cause the type-argument to terminate except comma token
20409                     return token() !== 27 /* CommaToken */;
20410                 case 22 /* HeritageClauses */:
20411                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20412                 case 13 /* JsxAttributes */:
20413                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20414                 case 14 /* JsxChildren */:
20415                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20416                 default:
20417                     return false;
20418             }
20419         }
20420         function isVariableDeclaratorListTerminator() {
20421             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20422             // with parsing the list of variable declarators.
20423             if (canParseSemicolon()) {
20424                 return true;
20425             }
20426             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20427             // are done if we see an 'in' keyword in front of us. Same with for-of
20428             if (isInOrOfKeyword(token())) {
20429                 return true;
20430             }
20431             // ERROR RECOVERY TWEAK:
20432             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20433             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20434             // another variable declaration.
20435             if (token() === 38 /* EqualsGreaterThanToken */) {
20436                 return true;
20437             }
20438             // Keep trying to parse out variable declarators.
20439             return false;
20440         }
20441         // True if positioned at element or terminator of the current list or any enclosing list
20442         function isInSomeParsingContext() {
20443             for (var kind = 0; kind < 24 /* Count */; kind++) {
20444                 if (parsingContext & (1 << kind)) {
20445                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20446                         return true;
20447                     }
20448                 }
20449             }
20450             return false;
20451         }
20452         // Parses a list of elements
20453         function parseList(kind, parseElement) {
20454             var saveParsingContext = parsingContext;
20455             parsingContext |= 1 << kind;
20456             var list = [];
20457             var listPos = getNodePos();
20458             while (!isListTerminator(kind)) {
20459                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20460                     var element = parseListElement(kind, parseElement);
20461                     list.push(element);
20462                     continue;
20463                 }
20464                 if (abortParsingListOrMoveToNextToken(kind)) {
20465                     break;
20466                 }
20467             }
20468             parsingContext = saveParsingContext;
20469             return createNodeArray(list, listPos);
20470         }
20471         function parseListElement(parsingContext, parseElement) {
20472             var node = currentNode(parsingContext);
20473             if (node) {
20474                 return consumeNode(node);
20475             }
20476             return parseElement();
20477         }
20478         function currentNode(parsingContext) {
20479             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20480             //
20481             // If there is an outstanding parse error that we've encountered, but not attached to
20482             // some node, then we cannot get a node from the old source tree.  This is because we
20483             // want to mark the next node we encounter as being unusable.
20484             //
20485             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20486             // on it (or its leftmost child) as having the error.  For now though, being conservative
20487             // is nice and likely won't ever affect perf.
20488             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20489                 return undefined;
20490             }
20491             var node = syntaxCursor.currentNode(scanner.getStartPos());
20492             // Can't reuse a missing node.
20493             // Can't reuse a node that intersected the change range.
20494             // Can't reuse a node that contains a parse error.  This is necessary so that we
20495             // produce the same set of errors again.
20496             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20497                 return undefined;
20498             }
20499             // We can only reuse a node if it was parsed under the same strict mode that we're
20500             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20501             // the user added 'using strict' at the top of the file, then we can't use that node
20502             // again as the presence of strict mode may cause us to parse the tokens in the file
20503             // differently.
20504             //
20505             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20506             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20507             // differently depending on what mode it is in.
20508             //
20509             // This also applies to all our other context flags as well.
20510             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20511             if (nodeContextFlags !== contextFlags) {
20512                 return undefined;
20513             }
20514             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20515             // in the current list parsing context that we're currently at.
20516             if (!canReuseNode(node, parsingContext)) {
20517                 return undefined;
20518             }
20519             if (node.jsDocCache) {
20520                 // jsDocCache may include tags from parent nodes, which might have been modified.
20521                 node.jsDocCache = undefined;
20522             }
20523             return node;
20524         }
20525         function consumeNode(node) {
20526             // Move the scanner so it is after the node we just consumed.
20527             scanner.setTextPos(node.end);
20528             nextToken();
20529             return node;
20530         }
20531         function isReusableParsingContext(parsingContext) {
20532             switch (parsingContext) {
20533                 case 5 /* ClassMembers */:
20534                 case 2 /* SwitchClauses */:
20535                 case 0 /* SourceElements */:
20536                 case 1 /* BlockStatements */:
20537                 case 3 /* SwitchClauseStatements */:
20538                 case 6 /* EnumMembers */:
20539                 case 4 /* TypeMembers */:
20540                 case 8 /* VariableDeclarations */:
20541                 case 17 /* JSDocParameters */:
20542                 case 16 /* Parameters */:
20543                     return true;
20544             }
20545             return false;
20546         }
20547         function canReuseNode(node, parsingContext) {
20548             switch (parsingContext) {
20549                 case 5 /* ClassMembers */:
20550                     return isReusableClassMember(node);
20551                 case 2 /* SwitchClauses */:
20552                     return isReusableSwitchClause(node);
20553                 case 0 /* SourceElements */:
20554                 case 1 /* BlockStatements */:
20555                 case 3 /* SwitchClauseStatements */:
20556                     return isReusableStatement(node);
20557                 case 6 /* EnumMembers */:
20558                     return isReusableEnumMember(node);
20559                 case 4 /* TypeMembers */:
20560                     return isReusableTypeMember(node);
20561                 case 8 /* VariableDeclarations */:
20562                     return isReusableVariableDeclaration(node);
20563                 case 17 /* JSDocParameters */:
20564                 case 16 /* Parameters */:
20565                     return isReusableParameter(node);
20566                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20567                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20568                 // parsing.  If speculative parsing is involved with the node, then the range the
20569                 // parser reached while looking ahead might be in the edited range (see the example
20570                 // in canReuseVariableDeclaratorNode for a good case of this).
20571                 // case ParsingContext.HeritageClauses:
20572                 // This would probably be safe to reuse.  There is no speculative parsing with
20573                 // heritage clauses.
20574                 // case ParsingContext.TypeParameters:
20575                 // This would probably be safe to reuse.  There is no speculative parsing with
20576                 // type parameters.  Note that that's because type *parameters* only occur in
20577                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20578                 // *expression* contexts.
20579                 // case ParsingContext.TupleElementTypes:
20580                 // This would probably be safe to reuse.  There is no speculative parsing with
20581                 // tuple types.
20582                 // Technically, type argument list types are probably safe to reuse.  While
20583                 // speculative parsing is involved with them (since type argument lists are only
20584                 // produced from speculative parsing a < as a type argument list), we only have
20585                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20586                 // went past the end of the list and rewound.
20587                 // case ParsingContext.TypeArguments:
20588                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20589                 // need a large amount of lookahead, and we should not reuse them as they may
20590                 // have actually intersected the edit.
20591                 // case ParsingContext.ArgumentExpressions:
20592                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20593                 // cases.  i.e. a property assignment may end with an expression, and thus might
20594                 // have lookahead far beyond it's old node.
20595                 // case ParsingContext.ObjectLiteralMembers:
20596                 // This is probably not safe to reuse.  There can be speculative parsing with
20597                 // type names in a heritage clause.  There can be generic names in the type
20598                 // name list, and there can be left hand side expressions (which can have type
20599                 // arguments.)
20600                 // case ParsingContext.HeritageClauseElement:
20601                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20602                 // on any given element. Same for children.
20603                 // case ParsingContext.JsxAttributes:
20604                 // case ParsingContext.JsxChildren:
20605             }
20606             return false;
20607         }
20608         function isReusableClassMember(node) {
20609             if (node) {
20610                 switch (node.kind) {
20611                     case 162 /* Constructor */:
20612                     case 167 /* IndexSignature */:
20613                     case 163 /* GetAccessor */:
20614                     case 164 /* SetAccessor */:
20615                     case 159 /* PropertyDeclaration */:
20616                     case 222 /* SemicolonClassElement */:
20617                         return true;
20618                     case 161 /* MethodDeclaration */:
20619                         // Method declarations are not necessarily reusable.  An object-literal
20620                         // may have a method calls "constructor(...)" and we must reparse that
20621                         // into an actual .ConstructorDeclaration.
20622                         var methodDeclaration = node;
20623                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20624                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20625                         return !nameIsConstructor;
20626                 }
20627             }
20628             return false;
20629         }
20630         function isReusableSwitchClause(node) {
20631             if (node) {
20632                 switch (node.kind) {
20633                     case 277 /* CaseClause */:
20634                     case 278 /* DefaultClause */:
20635                         return true;
20636                 }
20637             }
20638             return false;
20639         }
20640         function isReusableStatement(node) {
20641             if (node) {
20642                 switch (node.kind) {
20643                     case 244 /* FunctionDeclaration */:
20644                     case 225 /* VariableStatement */:
20645                     case 223 /* Block */:
20646                     case 227 /* IfStatement */:
20647                     case 226 /* ExpressionStatement */:
20648                     case 239 /* ThrowStatement */:
20649                     case 235 /* ReturnStatement */:
20650                     case 237 /* SwitchStatement */:
20651                     case 234 /* BreakStatement */:
20652                     case 233 /* ContinueStatement */:
20653                     case 231 /* ForInStatement */:
20654                     case 232 /* ForOfStatement */:
20655                     case 230 /* ForStatement */:
20656                     case 229 /* WhileStatement */:
20657                     case 236 /* WithStatement */:
20658                     case 224 /* EmptyStatement */:
20659                     case 240 /* TryStatement */:
20660                     case 238 /* LabeledStatement */:
20661                     case 228 /* DoStatement */:
20662                     case 241 /* DebuggerStatement */:
20663                     case 254 /* ImportDeclaration */:
20664                     case 253 /* ImportEqualsDeclaration */:
20665                     case 260 /* ExportDeclaration */:
20666                     case 259 /* ExportAssignment */:
20667                     case 249 /* ModuleDeclaration */:
20668                     case 245 /* ClassDeclaration */:
20669                     case 246 /* InterfaceDeclaration */:
20670                     case 248 /* EnumDeclaration */:
20671                     case 247 /* TypeAliasDeclaration */:
20672                         return true;
20673                 }
20674             }
20675             return false;
20676         }
20677         function isReusableEnumMember(node) {
20678             return node.kind === 284 /* EnumMember */;
20679         }
20680         function isReusableTypeMember(node) {
20681             if (node) {
20682                 switch (node.kind) {
20683                     case 166 /* ConstructSignature */:
20684                     case 160 /* MethodSignature */:
20685                     case 167 /* IndexSignature */:
20686                     case 158 /* PropertySignature */:
20687                     case 165 /* CallSignature */:
20688                         return true;
20689                 }
20690             }
20691             return false;
20692         }
20693         function isReusableVariableDeclaration(node) {
20694             if (node.kind !== 242 /* VariableDeclaration */) {
20695                 return false;
20696             }
20697             // Very subtle incremental parsing bug.  Consider the following code:
20698             //
20699             //      let v = new List < A, B
20700             //
20701             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20702             // on one side and "B" on the other. If you then change that to:
20703             //
20704             //      let v = new List < A, B >()
20705             //
20706             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20707             // start reparsing at "B" and we completely fail to handle this properly.
20708             //
20709             // In order to prevent this, we do not allow a variable declarator to be reused if it
20710             // has an initializer.
20711             var variableDeclarator = node;
20712             return variableDeclarator.initializer === undefined;
20713         }
20714         function isReusableParameter(node) {
20715             if (node.kind !== 156 /* Parameter */) {
20716                 return false;
20717             }
20718             // See the comment in isReusableVariableDeclaration for why we do this.
20719             var parameter = node;
20720             return parameter.initializer === undefined;
20721         }
20722         // Returns true if we should abort parsing.
20723         function abortParsingListOrMoveToNextToken(kind) {
20724             parseErrorAtCurrentToken(parsingContextErrors(kind));
20725             if (isInSomeParsingContext()) {
20726                 return true;
20727             }
20728             nextToken();
20729             return false;
20730         }
20731         function parsingContextErrors(context) {
20732             switch (context) {
20733                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20734                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20735                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20736                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20737                 case 18 /* RestProperties */: // fallthrough
20738                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20739                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20740                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20741                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20742                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20743                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20744                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20745                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20746                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20747                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20748                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20749                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20750                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20751                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20752                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20753                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20754                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20755                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20756                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20757                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20758             }
20759         }
20760         // Parses a comma-delimited list of elements
20761         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20762             var saveParsingContext = parsingContext;
20763             parsingContext |= 1 << kind;
20764             var list = [];
20765             var listPos = getNodePos();
20766             var commaStart = -1; // Meaning the previous token was not a comma
20767             while (true) {
20768                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20769                     var startPos = scanner.getStartPos();
20770                     list.push(parseListElement(kind, parseElement));
20771                     commaStart = scanner.getTokenPos();
20772                     if (parseOptional(27 /* CommaToken */)) {
20773                         // No need to check for a zero length node since we know we parsed a comma
20774                         continue;
20775                     }
20776                     commaStart = -1; // Back to the state where the last token was not a comma
20777                     if (isListTerminator(kind)) {
20778                         break;
20779                     }
20780                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20781                     // out a comma so we give a good error message.
20782                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20783                     // If the token was a semicolon, and the caller allows that, then skip it and
20784                     // continue.  This ensures we get back on track and don't result in tons of
20785                     // parse errors.  For example, this can happen when people do things like use
20786                     // a semicolon to delimit object literal members.   Note: we'll have already
20787                     // reported an error when we called parseExpected above.
20788                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20789                         nextToken();
20790                     }
20791                     if (startPos === scanner.getStartPos()) {
20792                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20793                         // Consume a token to advance the parser in some way and avoid an infinite loop
20794                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20795                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20796                         nextToken();
20797                     }
20798                     continue;
20799                 }
20800                 if (isListTerminator(kind)) {
20801                     break;
20802                 }
20803                 if (abortParsingListOrMoveToNextToken(kind)) {
20804                     break;
20805                 }
20806             }
20807             parsingContext = saveParsingContext;
20808             var result = createNodeArray(list, listPos);
20809             // Recording the trailing comma is deliberately done after the previous
20810             // loop, and not just if we see a list terminator. This is because the list
20811             // may have ended incorrectly, but it is still important to know if there
20812             // was a trailing comma.
20813             // Check if the last token was a comma.
20814             if (commaStart >= 0) {
20815                 // Always preserve a trailing comma by marking it on the NodeArray
20816                 result.hasTrailingComma = true;
20817             }
20818             return result;
20819         }
20820         function getExpectedCommaDiagnostic(kind) {
20821             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20822         }
20823         function createMissingList() {
20824             var list = createNodeArray([], getNodePos());
20825             list.isMissingList = true;
20826             return list;
20827         }
20828         function isMissingList(arr) {
20829             return !!arr.isMissingList;
20830         }
20831         function parseBracketedList(kind, parseElement, open, close) {
20832             if (parseExpected(open)) {
20833                 var result = parseDelimitedList(kind, parseElement);
20834                 parseExpected(close);
20835                 return result;
20836             }
20837             return createMissingList();
20838         }
20839         function parseEntityName(allowReservedWords, diagnosticMessage) {
20840             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
20841             var dotPos = scanner.getStartPos();
20842             while (parseOptional(24 /* DotToken */)) {
20843                 if (token() === 29 /* LessThanToken */) {
20844                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
20845                     entity.jsdocDotPos = dotPos;
20846                     break;
20847                 }
20848                 dotPos = scanner.getStartPos();
20849                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
20850             }
20851             return entity;
20852         }
20853         function createQualifiedName(entity, name) {
20854             var node = createNode(153 /* QualifiedName */, entity.pos);
20855             node.left = entity;
20856             node.right = name;
20857             return finishNode(node);
20858         }
20859         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
20860             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
20861             // However, often we'll encounter this in error situations when the identifier or keyword
20862             // is actually starting another valid construct.
20863             //
20864             // So, we check for the following specific case:
20865             //
20866             //      name.
20867             //      identifierOrKeyword identifierNameOrKeyword
20868             //
20869             // Note: the newlines are important here.  For example, if that above code
20870             // were rewritten into:
20871             //
20872             //      name.identifierOrKeyword
20873             //      identifierNameOrKeyword
20874             //
20875             // Then we would consider it valid.  That's because ASI would take effect and
20876             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
20877             // In the first case though, ASI will not take effect because there is not a
20878             // line terminator after the identifier or keyword.
20879             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
20880                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
20881                 if (matchesPattern) {
20882                     // Report that we need an identifier.  However, report it right after the dot,
20883                     // and not on the next token.  This is because the next token might actually
20884                     // be an identifier and the error would be quite confusing.
20885                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20886                 }
20887             }
20888             if (token() === 76 /* PrivateIdentifier */) {
20889                 var node = parsePrivateIdentifier();
20890                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20891             }
20892             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
20893         }
20894         function parseTemplateExpression(isTaggedTemplate) {
20895             var template = createNode(211 /* TemplateExpression */);
20896             template.head = parseTemplateHead(isTaggedTemplate);
20897             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20898             var list = [];
20899             var listPos = getNodePos();
20900             do {
20901                 list.push(parseTemplateSpan(isTaggedTemplate));
20902             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
20903             template.templateSpans = createNodeArray(list, listPos);
20904             return finishNode(template);
20905         }
20906         function parseTemplateSpan(isTaggedTemplate) {
20907             var span = createNode(221 /* TemplateSpan */);
20908             span.expression = allowInAnd(parseExpression);
20909             var literal;
20910             if (token() === 19 /* CloseBraceToken */) {
20911                 reScanTemplateToken(isTaggedTemplate);
20912                 literal = parseTemplateMiddleOrTemplateTail();
20913             }
20914             else {
20915                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
20916             }
20917             span.literal = literal;
20918             return finishNode(span);
20919         }
20920         function parseLiteralNode() {
20921             return parseLiteralLikeNode(token());
20922         }
20923         function parseTemplateHead(isTaggedTemplate) {
20924             if (isTaggedTemplate) {
20925                 reScanTemplateHeadOrNoSubstitutionTemplate();
20926             }
20927             var fragment = parseLiteralLikeNode(token());
20928             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20929             return fragment;
20930         }
20931         function parseTemplateMiddleOrTemplateTail() {
20932             var fragment = parseLiteralLikeNode(token());
20933             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
20934             return fragment;
20935         }
20936         function parseLiteralLikeNode(kind) {
20937             var node = createNode(kind);
20938             node.text = scanner.getTokenValue();
20939             switch (kind) {
20940                 case 14 /* NoSubstitutionTemplateLiteral */:
20941                 case 15 /* TemplateHead */:
20942                 case 16 /* TemplateMiddle */:
20943                 case 17 /* TemplateTail */:
20944                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
20945                     var tokenText = scanner.getTokenText();
20946                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
20947                     break;
20948             }
20949             if (scanner.hasExtendedUnicodeEscape()) {
20950                 node.hasExtendedUnicodeEscape = true;
20951             }
20952             if (scanner.isUnterminated()) {
20953                 node.isUnterminated = true;
20954             }
20955             // Octal literals are not allowed in strict mode or ES5
20956             // Note that theoretically the following condition would hold true literals like 009,
20957             // which is not octal.But because of how the scanner separates the tokens, we would
20958             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
20959             // We also do not need to check for negatives because any prefix operator would be part of a
20960             // parent unary expression.
20961             if (node.kind === 8 /* NumericLiteral */) {
20962                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
20963             }
20964             if (ts.isTemplateLiteralKind(node.kind)) {
20965                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
20966             }
20967             nextToken();
20968             finishNode(node);
20969             return node;
20970         }
20971         // TYPES
20972         function parseTypeReference() {
20973             var node = createNode(169 /* TypeReference */);
20974             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
20975             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
20976                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
20977             }
20978             return finishNode(node);
20979         }
20980         // If true, we should abort parsing an error function.
20981         function typeHasArrowFunctionBlockingParseError(node) {
20982             switch (node.kind) {
20983                 case 169 /* TypeReference */:
20984                     return ts.nodeIsMissing(node.typeName);
20985                 case 170 /* FunctionType */:
20986                 case 171 /* ConstructorType */: {
20987                     var _a = node, parameters = _a.parameters, type = _a.type;
20988                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
20989                 }
20990                 case 182 /* ParenthesizedType */:
20991                     return typeHasArrowFunctionBlockingParseError(node.type);
20992                 default:
20993                     return false;
20994             }
20995         }
20996         function parseThisTypePredicate(lhs) {
20997             nextToken();
20998             var node = createNode(168 /* TypePredicate */, lhs.pos);
20999             node.parameterName = lhs;
21000             node.type = parseType();
21001             return finishNode(node);
21002         }
21003         function parseThisTypeNode() {
21004             var node = createNode(183 /* ThisType */);
21005             nextToken();
21006             return finishNode(node);
21007         }
21008         function parseJSDocAllType(postFixEquals) {
21009             var result = createNode(295 /* JSDocAllType */);
21010             if (postFixEquals) {
21011                 return createPostfixType(299 /* JSDocOptionalType */, result);
21012             }
21013             else {
21014                 nextToken();
21015             }
21016             return finishNode(result);
21017         }
21018         function parseJSDocNonNullableType() {
21019             var result = createNode(298 /* JSDocNonNullableType */);
21020             nextToken();
21021             result.type = parseNonArrayType();
21022             return finishNode(result);
21023         }
21024         function parseJSDocUnknownOrNullableType() {
21025             var pos = scanner.getStartPos();
21026             // skip the ?
21027             nextToken();
21028             // Need to lookahead to decide if this is a nullable or unknown type.
21029             // Here are cases where we'll pick the unknown type:
21030             //
21031             //      Foo(?,
21032             //      { a: ? }
21033             //      Foo(?)
21034             //      Foo<?>
21035             //      Foo(?=
21036             //      (?|
21037             if (token() === 27 /* CommaToken */ ||
21038                 token() === 19 /* CloseBraceToken */ ||
21039                 token() === 21 /* CloseParenToken */ ||
21040                 token() === 31 /* GreaterThanToken */ ||
21041                 token() === 62 /* EqualsToken */ ||
21042                 token() === 51 /* BarToken */) {
21043                 var result = createNode(296 /* JSDocUnknownType */, pos);
21044                 return finishNode(result);
21045             }
21046             else {
21047                 var result = createNode(297 /* JSDocNullableType */, pos);
21048                 result.type = parseType();
21049                 return finishNode(result);
21050             }
21051         }
21052         function parseJSDocFunctionType() {
21053             if (lookAhead(nextTokenIsOpenParen)) {
21054                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21055                 nextToken();
21056                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21057                 return finishNode(result);
21058             }
21059             var node = createNode(169 /* TypeReference */);
21060             node.typeName = parseIdentifierName();
21061             return finishNode(node);
21062         }
21063         function parseJSDocParameter() {
21064             var parameter = createNode(156 /* Parameter */);
21065             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21066                 parameter.name = parseIdentifierName();
21067                 parseExpected(58 /* ColonToken */);
21068             }
21069             parameter.type = parseJSDocType();
21070             return finishNode(parameter);
21071         }
21072         function parseJSDocType() {
21073             scanner.setInJSDocType(true);
21074             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21075             if (moduleSpecifier) {
21076                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21077                 terminate: while (true) {
21078                     switch (token()) {
21079                         case 19 /* CloseBraceToken */:
21080                         case 1 /* EndOfFileToken */:
21081                         case 27 /* CommaToken */:
21082                         case 5 /* WhitespaceTrivia */:
21083                             break terminate;
21084                         default:
21085                             nextTokenJSDoc();
21086                     }
21087                 }
21088                 scanner.setInJSDocType(false);
21089                 return finishNode(moduleTag);
21090             }
21091             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21092             var type = parseTypeOrTypePredicate();
21093             scanner.setInJSDocType(false);
21094             if (dotdotdot) {
21095                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21096                 variadic.type = type;
21097                 type = finishNode(variadic);
21098             }
21099             if (token() === 62 /* EqualsToken */) {
21100                 return createPostfixType(299 /* JSDocOptionalType */, type);
21101             }
21102             return type;
21103         }
21104         function parseTypeQuery() {
21105             var node = createNode(172 /* TypeQuery */);
21106             parseExpected(108 /* TypeOfKeyword */);
21107             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21108             return finishNode(node);
21109         }
21110         function parseTypeParameter() {
21111             var node = createNode(155 /* TypeParameter */);
21112             node.name = parseIdentifier();
21113             if (parseOptional(90 /* ExtendsKeyword */)) {
21114                 // It's not uncommon for people to write improper constraints to a generic.  If the
21115                 // user writes a constraint that is an expression and not an actual type, then parse
21116                 // it out as an expression (so we can recover well), but report that a type is needed
21117                 // instead.
21118                 if (isStartOfType() || !isStartOfExpression()) {
21119                     node.constraint = parseType();
21120                 }
21121                 else {
21122                     // It was not a type, and it looked like an expression.  Parse out an expression
21123                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21124                     // and not parseExpression here.  If the user has:
21125                     //
21126                     //      <T extends "">
21127                     //
21128                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21129                     node.expression = parseUnaryExpressionOrHigher();
21130                 }
21131             }
21132             if (parseOptional(62 /* EqualsToken */)) {
21133                 node.default = parseType();
21134             }
21135             return finishNode(node);
21136         }
21137         function parseTypeParameters() {
21138             if (token() === 29 /* LessThanToken */) {
21139                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21140             }
21141         }
21142         function parseParameterType() {
21143             if (parseOptional(58 /* ColonToken */)) {
21144                 return parseType();
21145             }
21146             return undefined;
21147         }
21148         function isStartOfParameter(isJSDocParameter) {
21149             return token() === 25 /* DotDotDotToken */ ||
21150                 isIdentifierOrPrivateIdentifierOrPattern() ||
21151                 ts.isModifierKind(token()) ||
21152                 token() === 59 /* AtToken */ ||
21153                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21154         }
21155         function parseParameter() {
21156             var node = createNodeWithJSDoc(156 /* Parameter */);
21157             if (token() === 104 /* ThisKeyword */) {
21158                 node.name = createIdentifier(/*isIdentifier*/ true);
21159                 node.type = parseParameterType();
21160                 return finishNode(node);
21161             }
21162             node.decorators = parseDecorators();
21163             node.modifiers = parseModifiers();
21164             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21165             // FormalParameter [Yield,Await]:
21166             //      BindingElement[?Yield,?Await]
21167             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21168             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21169                 // in cases like
21170                 // 'use strict'
21171                 // function foo(static)
21172                 // isParameter('static') === true, because of isModifier('static')
21173                 // however 'static' is not a legal identifier in a strict mode.
21174                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21175                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21176                 // to avoid this we'll advance cursor to the next token.
21177                 nextToken();
21178             }
21179             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21180             node.type = parseParameterType();
21181             node.initializer = parseInitializer();
21182             return finishNode(node);
21183         }
21184         /**
21185          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21186          * @returns If return type parsing succeeds
21187          */
21188         function fillSignature(returnToken, flags, signature) {
21189             if (!(flags & 32 /* JSDoc */)) {
21190                 signature.typeParameters = parseTypeParameters();
21191             }
21192             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21193             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21194                 signature.type = parseTypeOrTypePredicate();
21195                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21196                     return false;
21197             }
21198             return parametersParsedSuccessfully;
21199         }
21200         function shouldParseReturnType(returnToken, isType) {
21201             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21202                 parseExpected(returnToken);
21203                 return true;
21204             }
21205             else if (parseOptional(58 /* ColonToken */)) {
21206                 return true;
21207             }
21208             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21209                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21210                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21211                 nextToken();
21212                 return true;
21213             }
21214             return false;
21215         }
21216         // Returns true on success.
21217         function parseParameterList(signature, flags) {
21218             // FormalParameters [Yield,Await]: (modified)
21219             //      [empty]
21220             //      FormalParameterList[?Yield,Await]
21221             //
21222             // FormalParameter[Yield,Await]: (modified)
21223             //      BindingElement[?Yield,Await]
21224             //
21225             // BindingElement [Yield,Await]: (modified)
21226             //      SingleNameBinding[?Yield,?Await]
21227             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21228             //
21229             // SingleNameBinding [Yield,Await]:
21230             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21231             if (!parseExpected(20 /* OpenParenToken */)) {
21232                 signature.parameters = createMissingList();
21233                 return false;
21234             }
21235             var savedYieldContext = inYieldContext();
21236             var savedAwaitContext = inAwaitContext();
21237             setYieldContext(!!(flags & 1 /* Yield */));
21238             setAwaitContext(!!(flags & 2 /* Await */));
21239             signature.parameters = flags & 32 /* JSDoc */ ?
21240                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21241                 parseDelimitedList(16 /* Parameters */, parseParameter);
21242             setYieldContext(savedYieldContext);
21243             setAwaitContext(savedAwaitContext);
21244             return parseExpected(21 /* CloseParenToken */);
21245         }
21246         function parseTypeMemberSemicolon() {
21247             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21248             // First check if it was a comma.  If so, we're done with the member.
21249             if (parseOptional(27 /* CommaToken */)) {
21250                 return;
21251             }
21252             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21253             parseSemicolon();
21254         }
21255         function parseSignatureMember(kind) {
21256             var node = createNodeWithJSDoc(kind);
21257             if (kind === 166 /* ConstructSignature */) {
21258                 parseExpected(99 /* NewKeyword */);
21259             }
21260             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21261             parseTypeMemberSemicolon();
21262             return finishNode(node);
21263         }
21264         function isIndexSignature() {
21265             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21266         }
21267         function isUnambiguouslyIndexSignature() {
21268             // The only allowed sequence is:
21269             //
21270             //   [id:
21271             //
21272             // However, for error recovery, we also check the following cases:
21273             //
21274             //   [...
21275             //   [id,
21276             //   [id?,
21277             //   [id?:
21278             //   [id?]
21279             //   [public id
21280             //   [private id
21281             //   [protected id
21282             //   []
21283             //
21284             nextToken();
21285             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21286                 return true;
21287             }
21288             if (ts.isModifierKind(token())) {
21289                 nextToken();
21290                 if (isIdentifier()) {
21291                     return true;
21292                 }
21293             }
21294             else if (!isIdentifier()) {
21295                 return false;
21296             }
21297             else {
21298                 // Skip the identifier
21299                 nextToken();
21300             }
21301             // A colon signifies a well formed indexer
21302             // A comma should be a badly formed indexer because comma expressions are not allowed
21303             // in computed properties.
21304             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21305                 return true;
21306             }
21307             // Question mark could be an indexer with an optional property,
21308             // or it could be a conditional expression in a computed property.
21309             if (token() !== 57 /* QuestionToken */) {
21310                 return false;
21311             }
21312             // If any of the following tokens are after the question mark, it cannot
21313             // be a conditional expression, so treat it as an indexer.
21314             nextToken();
21315             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21316         }
21317         function parseIndexSignatureDeclaration(node) {
21318             node.kind = 167 /* IndexSignature */;
21319             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21320             node.type = parseTypeAnnotation();
21321             parseTypeMemberSemicolon();
21322             return finishNode(node);
21323         }
21324         function parsePropertyOrMethodSignature(node) {
21325             node.name = parsePropertyName();
21326             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21327             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21328                 node.kind = 160 /* MethodSignature */;
21329                 // Method signatures don't exist in expression contexts.  So they have neither
21330                 // [Yield] nor [Await]
21331                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21332             }
21333             else {
21334                 node.kind = 158 /* PropertySignature */;
21335                 node.type = parseTypeAnnotation();
21336                 if (token() === 62 /* EqualsToken */) {
21337                     // Although type literal properties cannot not have initializers, we attempt
21338                     // to parse an initializer so we can report in the checker that an interface
21339                     // property or type literal property cannot have an initializer.
21340                     node.initializer = parseInitializer();
21341                 }
21342             }
21343             parseTypeMemberSemicolon();
21344             return finishNode(node);
21345         }
21346         function isTypeMemberStart() {
21347             // Return true if we have the start of a signature member
21348             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21349                 return true;
21350             }
21351             var idToken = false;
21352             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21353             while (ts.isModifierKind(token())) {
21354                 idToken = true;
21355                 nextToken();
21356             }
21357             // Index signatures and computed property names are type members
21358             if (token() === 22 /* OpenBracketToken */) {
21359                 return true;
21360             }
21361             // Try to get the first property-like token following all modifiers
21362             if (isLiteralPropertyName()) {
21363                 idToken = true;
21364                 nextToken();
21365             }
21366             // If we were able to get any potential identifier, check that it is
21367             // the start of a member declaration
21368             if (idToken) {
21369                 return token() === 20 /* OpenParenToken */ ||
21370                     token() === 29 /* LessThanToken */ ||
21371                     token() === 57 /* QuestionToken */ ||
21372                     token() === 58 /* ColonToken */ ||
21373                     token() === 27 /* CommaToken */ ||
21374                     canParseSemicolon();
21375             }
21376             return false;
21377         }
21378         function parseTypeMember() {
21379             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21380                 return parseSignatureMember(165 /* CallSignature */);
21381             }
21382             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21383                 return parseSignatureMember(166 /* ConstructSignature */);
21384             }
21385             var node = createNodeWithJSDoc(0 /* Unknown */);
21386             node.modifiers = parseModifiers();
21387             if (isIndexSignature()) {
21388                 return parseIndexSignatureDeclaration(node);
21389             }
21390             return parsePropertyOrMethodSignature(node);
21391         }
21392         function nextTokenIsOpenParenOrLessThan() {
21393             nextToken();
21394             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21395         }
21396         function nextTokenIsDot() {
21397             return nextToken() === 24 /* DotToken */;
21398         }
21399         function nextTokenIsOpenParenOrLessThanOrDot() {
21400             switch (nextToken()) {
21401                 case 20 /* OpenParenToken */:
21402                 case 29 /* LessThanToken */:
21403                 case 24 /* DotToken */:
21404                     return true;
21405             }
21406             return false;
21407         }
21408         function parseTypeLiteral() {
21409             var node = createNode(173 /* TypeLiteral */);
21410             node.members = parseObjectTypeMembers();
21411             return finishNode(node);
21412         }
21413         function parseObjectTypeMembers() {
21414             var members;
21415             if (parseExpected(18 /* OpenBraceToken */)) {
21416                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21417                 parseExpected(19 /* CloseBraceToken */);
21418             }
21419             else {
21420                 members = createMissingList();
21421             }
21422             return members;
21423         }
21424         function isStartOfMappedType() {
21425             nextToken();
21426             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21427                 return nextToken() === 138 /* ReadonlyKeyword */;
21428             }
21429             if (token() === 138 /* ReadonlyKeyword */) {
21430                 nextToken();
21431             }
21432             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21433         }
21434         function parseMappedTypeParameter() {
21435             var node = createNode(155 /* TypeParameter */);
21436             node.name = parseIdentifier();
21437             parseExpected(97 /* InKeyword */);
21438             node.constraint = parseType();
21439             return finishNode(node);
21440         }
21441         function parseMappedType() {
21442             var node = createNode(186 /* MappedType */);
21443             parseExpected(18 /* OpenBraceToken */);
21444             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21445                 node.readonlyToken = parseTokenNode();
21446                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21447                     parseExpectedToken(138 /* ReadonlyKeyword */);
21448                 }
21449             }
21450             parseExpected(22 /* OpenBracketToken */);
21451             node.typeParameter = parseMappedTypeParameter();
21452             parseExpected(23 /* CloseBracketToken */);
21453             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21454                 node.questionToken = parseTokenNode();
21455                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21456                     parseExpectedToken(57 /* QuestionToken */);
21457                 }
21458             }
21459             node.type = parseTypeAnnotation();
21460             parseSemicolon();
21461             parseExpected(19 /* CloseBraceToken */);
21462             return finishNode(node);
21463         }
21464         function parseTupleElementType() {
21465             var pos = getNodePos();
21466             if (parseOptional(25 /* DotDotDotToken */)) {
21467                 var node = createNode(177 /* RestType */, pos);
21468                 node.type = parseType();
21469                 return finishNode(node);
21470             }
21471             var type = parseType();
21472             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21473                 type.kind = 176 /* OptionalType */;
21474             }
21475             return type;
21476         }
21477         function parseTupleType() {
21478             var node = createNode(175 /* TupleType */);
21479             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21480             return finishNode(node);
21481         }
21482         function parseParenthesizedType() {
21483             var node = createNode(182 /* ParenthesizedType */);
21484             parseExpected(20 /* OpenParenToken */);
21485             node.type = parseType();
21486             parseExpected(21 /* CloseParenToken */);
21487             return finishNode(node);
21488         }
21489         function parseFunctionOrConstructorType() {
21490             var pos = getNodePos();
21491             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21492             var node = createNodeWithJSDoc(kind, pos);
21493             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21494             return finishNode(node);
21495         }
21496         function parseKeywordAndNoDot() {
21497             var node = parseTokenNode();
21498             return token() === 24 /* DotToken */ ? undefined : node;
21499         }
21500         function parseLiteralTypeNode(negative) {
21501             var node = createNode(187 /* LiteralType */);
21502             var unaryMinusExpression;
21503             if (negative) {
21504                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21505                 unaryMinusExpression.operator = 40 /* MinusToken */;
21506                 nextToken();
21507             }
21508             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21509                 ? parseTokenNode()
21510                 : parseLiteralLikeNode(token());
21511             if (negative) {
21512                 unaryMinusExpression.operand = expression;
21513                 finishNode(unaryMinusExpression);
21514                 expression = unaryMinusExpression;
21515             }
21516             node.literal = expression;
21517             return finishNode(node);
21518         }
21519         function isStartOfTypeOfImportType() {
21520             nextToken();
21521             return token() === 96 /* ImportKeyword */;
21522         }
21523         function parseImportType() {
21524             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21525             var node = createNode(188 /* ImportType */);
21526             if (parseOptional(108 /* TypeOfKeyword */)) {
21527                 node.isTypeOf = true;
21528             }
21529             parseExpected(96 /* ImportKeyword */);
21530             parseExpected(20 /* OpenParenToken */);
21531             node.argument = parseType();
21532             parseExpected(21 /* CloseParenToken */);
21533             if (parseOptional(24 /* DotToken */)) {
21534                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21535             }
21536             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21537                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21538             }
21539             return finishNode(node);
21540         }
21541         function nextTokenIsNumericOrBigIntLiteral() {
21542             nextToken();
21543             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21544         }
21545         function parseNonArrayType() {
21546             switch (token()) {
21547                 case 125 /* AnyKeyword */:
21548                 case 148 /* UnknownKeyword */:
21549                 case 143 /* StringKeyword */:
21550                 case 140 /* NumberKeyword */:
21551                 case 151 /* BigIntKeyword */:
21552                 case 144 /* SymbolKeyword */:
21553                 case 128 /* BooleanKeyword */:
21554                 case 146 /* UndefinedKeyword */:
21555                 case 137 /* NeverKeyword */:
21556                 case 141 /* ObjectKeyword */:
21557                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21558                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21559                 case 41 /* AsteriskToken */:
21560                     return parseJSDocAllType(/*postfixEquals*/ false);
21561                 case 65 /* AsteriskEqualsToken */:
21562                     return parseJSDocAllType(/*postfixEquals*/ true);
21563                 case 60 /* QuestionQuestionToken */:
21564                     // If there is '??', consider that is prefix '?' in JSDoc type.
21565                     scanner.reScanQuestionToken();
21566                 // falls through
21567                 case 57 /* QuestionToken */:
21568                     return parseJSDocUnknownOrNullableType();
21569                 case 94 /* FunctionKeyword */:
21570                     return parseJSDocFunctionType();
21571                 case 53 /* ExclamationToken */:
21572                     return parseJSDocNonNullableType();
21573                 case 14 /* NoSubstitutionTemplateLiteral */:
21574                 case 10 /* StringLiteral */:
21575                 case 8 /* NumericLiteral */:
21576                 case 9 /* BigIntLiteral */:
21577                 case 106 /* TrueKeyword */:
21578                 case 91 /* FalseKeyword */:
21579                     return parseLiteralTypeNode();
21580                 case 40 /* MinusToken */:
21581                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21582                 case 110 /* VoidKeyword */:
21583                 case 100 /* NullKeyword */:
21584                     return parseTokenNode();
21585                 case 104 /* ThisKeyword */: {
21586                     var thisKeyword = parseThisTypeNode();
21587                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21588                         return parseThisTypePredicate(thisKeyword);
21589                     }
21590                     else {
21591                         return thisKeyword;
21592                     }
21593                 }
21594                 case 108 /* TypeOfKeyword */:
21595                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21596                 case 18 /* OpenBraceToken */:
21597                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21598                 case 22 /* OpenBracketToken */:
21599                     return parseTupleType();
21600                 case 20 /* OpenParenToken */:
21601                     return parseParenthesizedType();
21602                 case 96 /* ImportKeyword */:
21603                     return parseImportType();
21604                 case 124 /* AssertsKeyword */:
21605                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21606                 default:
21607                     return parseTypeReference();
21608             }
21609         }
21610         function isStartOfType(inStartOfParameter) {
21611             switch (token()) {
21612                 case 125 /* AnyKeyword */:
21613                 case 148 /* UnknownKeyword */:
21614                 case 143 /* StringKeyword */:
21615                 case 140 /* NumberKeyword */:
21616                 case 151 /* BigIntKeyword */:
21617                 case 128 /* BooleanKeyword */:
21618                 case 138 /* ReadonlyKeyword */:
21619                 case 144 /* SymbolKeyword */:
21620                 case 147 /* UniqueKeyword */:
21621                 case 110 /* VoidKeyword */:
21622                 case 146 /* UndefinedKeyword */:
21623                 case 100 /* NullKeyword */:
21624                 case 104 /* ThisKeyword */:
21625                 case 108 /* TypeOfKeyword */:
21626                 case 137 /* NeverKeyword */:
21627                 case 18 /* OpenBraceToken */:
21628                 case 22 /* OpenBracketToken */:
21629                 case 29 /* LessThanToken */:
21630                 case 51 /* BarToken */:
21631                 case 50 /* AmpersandToken */:
21632                 case 99 /* NewKeyword */:
21633                 case 10 /* StringLiteral */:
21634                 case 8 /* NumericLiteral */:
21635                 case 9 /* BigIntLiteral */:
21636                 case 106 /* TrueKeyword */:
21637                 case 91 /* FalseKeyword */:
21638                 case 141 /* ObjectKeyword */:
21639                 case 41 /* AsteriskToken */:
21640                 case 57 /* QuestionToken */:
21641                 case 53 /* ExclamationToken */:
21642                 case 25 /* DotDotDotToken */:
21643                 case 132 /* InferKeyword */:
21644                 case 96 /* ImportKeyword */:
21645                 case 124 /* AssertsKeyword */:
21646                     return true;
21647                 case 94 /* FunctionKeyword */:
21648                     return !inStartOfParameter;
21649                 case 40 /* MinusToken */:
21650                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21651                 case 20 /* OpenParenToken */:
21652                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21653                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21654                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21655                 default:
21656                     return isIdentifier();
21657             }
21658         }
21659         function isStartOfParenthesizedOrFunctionType() {
21660             nextToken();
21661             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21662         }
21663         function parsePostfixTypeOrHigher() {
21664             var type = parseNonArrayType();
21665             while (!scanner.hasPrecedingLineBreak()) {
21666                 switch (token()) {
21667                     case 53 /* ExclamationToken */:
21668                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21669                         break;
21670                     case 57 /* QuestionToken */:
21671                         // If not in JSDoc and next token is start of a type we have a conditional type
21672                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21673                             return type;
21674                         }
21675                         type = createPostfixType(297 /* JSDocNullableType */, type);
21676                         break;
21677                     case 22 /* OpenBracketToken */:
21678                         parseExpected(22 /* OpenBracketToken */);
21679                         if (isStartOfType()) {
21680                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21681                             node.objectType = type;
21682                             node.indexType = parseType();
21683                             parseExpected(23 /* CloseBracketToken */);
21684                             type = finishNode(node);
21685                         }
21686                         else {
21687                             var node = createNode(174 /* ArrayType */, type.pos);
21688                             node.elementType = type;
21689                             parseExpected(23 /* CloseBracketToken */);
21690                             type = finishNode(node);
21691                         }
21692                         break;
21693                     default:
21694                         return type;
21695                 }
21696             }
21697             return type;
21698         }
21699         function createPostfixType(kind, type) {
21700             nextToken();
21701             var postfix = createNode(kind, type.pos);
21702             postfix.type = type;
21703             return finishNode(postfix);
21704         }
21705         function parseTypeOperator(operator) {
21706             var node = createNode(184 /* TypeOperator */);
21707             parseExpected(operator);
21708             node.operator = operator;
21709             node.type = parseTypeOperatorOrHigher();
21710             return finishNode(node);
21711         }
21712         function parseInferType() {
21713             var node = createNode(181 /* InferType */);
21714             parseExpected(132 /* InferKeyword */);
21715             var typeParameter = createNode(155 /* TypeParameter */);
21716             typeParameter.name = parseIdentifier();
21717             node.typeParameter = finishNode(typeParameter);
21718             return finishNode(node);
21719         }
21720         function parseTypeOperatorOrHigher() {
21721             var operator = token();
21722             switch (operator) {
21723                 case 134 /* KeyOfKeyword */:
21724                 case 147 /* UniqueKeyword */:
21725                 case 138 /* ReadonlyKeyword */:
21726                     return parseTypeOperator(operator);
21727                 case 132 /* InferKeyword */:
21728                     return parseInferType();
21729             }
21730             return parsePostfixTypeOrHigher();
21731         }
21732         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21733             var start = scanner.getStartPos();
21734             var hasLeadingOperator = parseOptional(operator);
21735             var type = parseConstituentType();
21736             if (token() === operator || hasLeadingOperator) {
21737                 var types = [type];
21738                 while (parseOptional(operator)) {
21739                     types.push(parseConstituentType());
21740                 }
21741                 var node = createNode(kind, start);
21742                 node.types = createNodeArray(types, start);
21743                 type = finishNode(node);
21744             }
21745             return type;
21746         }
21747         function parseIntersectionTypeOrHigher() {
21748             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21749         }
21750         function parseUnionTypeOrHigher() {
21751             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21752         }
21753         function isStartOfFunctionType() {
21754             if (token() === 29 /* LessThanToken */) {
21755                 return true;
21756             }
21757             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21758         }
21759         function skipParameterStart() {
21760             if (ts.isModifierKind(token())) {
21761                 // Skip modifiers
21762                 parseModifiers();
21763             }
21764             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21765                 nextToken();
21766                 return true;
21767             }
21768             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21769                 // Return true if we can parse an array or object binding pattern with no errors
21770                 var previousErrorCount = parseDiagnostics.length;
21771                 parseIdentifierOrPattern();
21772                 return previousErrorCount === parseDiagnostics.length;
21773             }
21774             return false;
21775         }
21776         function isUnambiguouslyStartOfFunctionType() {
21777             nextToken();
21778             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21779                 // ( )
21780                 // ( ...
21781                 return true;
21782             }
21783             if (skipParameterStart()) {
21784                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21785                 // now see if we have something that indicates a parameter declaration
21786                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21787                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21788                     // ( xxx :
21789                     // ( xxx ,
21790                     // ( xxx ?
21791                     // ( xxx =
21792                     return true;
21793                 }
21794                 if (token() === 21 /* CloseParenToken */) {
21795                     nextToken();
21796                     if (token() === 38 /* EqualsGreaterThanToken */) {
21797                         // ( xxx ) =>
21798                         return true;
21799                     }
21800                 }
21801             }
21802             return false;
21803         }
21804         function parseTypeOrTypePredicate() {
21805             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21806             var type = parseType();
21807             if (typePredicateVariable) {
21808                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21809                 node.assertsModifier = undefined;
21810                 node.parameterName = typePredicateVariable;
21811                 node.type = type;
21812                 return finishNode(node);
21813             }
21814             else {
21815                 return type;
21816             }
21817         }
21818         function parseTypePredicatePrefix() {
21819             var id = parseIdentifier();
21820             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21821                 nextToken();
21822                 return id;
21823             }
21824         }
21825         function parseAssertsTypePredicate() {
21826             var node = createNode(168 /* TypePredicate */);
21827             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21828             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21829             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21830             return finishNode(node);
21831         }
21832         function parseType() {
21833             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21834             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21835             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21836         }
21837         function parseTypeWorker(noConditionalTypes) {
21838             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
21839                 return parseFunctionOrConstructorType();
21840             }
21841             var type = parseUnionTypeOrHigher();
21842             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
21843                 var node = createNode(180 /* ConditionalType */, type.pos);
21844                 node.checkType = type;
21845                 // The type following 'extends' is not permitted to be another conditional type
21846                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
21847                 parseExpected(57 /* QuestionToken */);
21848                 node.trueType = parseTypeWorker();
21849                 parseExpected(58 /* ColonToken */);
21850                 node.falseType = parseTypeWorker();
21851                 return finishNode(node);
21852             }
21853             return type;
21854         }
21855         function parseTypeAnnotation() {
21856             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
21857         }
21858         // EXPRESSIONS
21859         function isStartOfLeftHandSideExpression() {
21860             switch (token()) {
21861                 case 104 /* ThisKeyword */:
21862                 case 102 /* SuperKeyword */:
21863                 case 100 /* NullKeyword */:
21864                 case 106 /* TrueKeyword */:
21865                 case 91 /* FalseKeyword */:
21866                 case 8 /* NumericLiteral */:
21867                 case 9 /* BigIntLiteral */:
21868                 case 10 /* StringLiteral */:
21869                 case 14 /* NoSubstitutionTemplateLiteral */:
21870                 case 15 /* TemplateHead */:
21871                 case 20 /* OpenParenToken */:
21872                 case 22 /* OpenBracketToken */:
21873                 case 18 /* OpenBraceToken */:
21874                 case 94 /* FunctionKeyword */:
21875                 case 80 /* ClassKeyword */:
21876                 case 99 /* NewKeyword */:
21877                 case 43 /* SlashToken */:
21878                 case 67 /* SlashEqualsToken */:
21879                 case 75 /* Identifier */:
21880                     return true;
21881                 case 96 /* ImportKeyword */:
21882                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21883                 default:
21884                     return isIdentifier();
21885             }
21886         }
21887         function isStartOfExpression() {
21888             if (isStartOfLeftHandSideExpression()) {
21889                 return true;
21890             }
21891             switch (token()) {
21892                 case 39 /* PlusToken */:
21893                 case 40 /* MinusToken */:
21894                 case 54 /* TildeToken */:
21895                 case 53 /* ExclamationToken */:
21896                 case 85 /* DeleteKeyword */:
21897                 case 108 /* TypeOfKeyword */:
21898                 case 110 /* VoidKeyword */:
21899                 case 45 /* PlusPlusToken */:
21900                 case 46 /* MinusMinusToken */:
21901                 case 29 /* LessThanToken */:
21902                 case 127 /* AwaitKeyword */:
21903                 case 121 /* YieldKeyword */:
21904                 case 76 /* PrivateIdentifier */:
21905                     // Yield/await always starts an expression.  Either it is an identifier (in which case
21906                     // it is definitely an expression).  Or it's a keyword (either because we're in
21907                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
21908                     return true;
21909                 default:
21910                     // Error tolerance.  If we see the start of some binary operator, we consider
21911                     // that the start of an expression.  That way we'll parse out a missing identifier,
21912                     // give a good message about an identifier being missing, and then consume the
21913                     // rest of the binary expression.
21914                     if (isBinaryOperator()) {
21915                         return true;
21916                     }
21917                     return isIdentifier();
21918             }
21919         }
21920         function isStartOfExpressionStatement() {
21921             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
21922             return token() !== 18 /* OpenBraceToken */ &&
21923                 token() !== 94 /* FunctionKeyword */ &&
21924                 token() !== 80 /* ClassKeyword */ &&
21925                 token() !== 59 /* AtToken */ &&
21926                 isStartOfExpression();
21927         }
21928         function parseExpression() {
21929             // Expression[in]:
21930             //      AssignmentExpression[in]
21931             //      Expression[in] , AssignmentExpression[in]
21932             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
21933             var saveDecoratorContext = inDecoratorContext();
21934             if (saveDecoratorContext) {
21935                 setDecoratorContext(/*val*/ false);
21936             }
21937             var expr = parseAssignmentExpressionOrHigher();
21938             var operatorToken;
21939             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
21940                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
21941             }
21942             if (saveDecoratorContext) {
21943                 setDecoratorContext(/*val*/ true);
21944             }
21945             return expr;
21946         }
21947         function parseInitializer() {
21948             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
21949         }
21950         function parseAssignmentExpressionOrHigher() {
21951             //  AssignmentExpression[in,yield]:
21952             //      1) ConditionalExpression[?in,?yield]
21953             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
21954             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
21955             //      4) ArrowFunctionExpression[?in,?yield]
21956             //      5) AsyncArrowFunctionExpression[in,yield,await]
21957             //      6) [+Yield] YieldExpression[?In]
21958             //
21959             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
21960             // (i.e. they're both BinaryExpressions with an assignment operator in it).
21961             // First, do the simple check if we have a YieldExpression (production '6').
21962             if (isYieldExpression()) {
21963                 return parseYieldExpression();
21964             }
21965             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
21966             // parameter list or is an async arrow function.
21967             // AsyncArrowFunctionExpression:
21968             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
21969             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
21970             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
21971             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
21972             //
21973             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
21974             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
21975             // with AssignmentExpression if we see one.
21976             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
21977             if (arrowExpression) {
21978                 return arrowExpression;
21979             }
21980             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
21981             // start with a LogicalOrExpression, while the assignment productions can only start with
21982             // LeftHandSideExpressions.
21983             //
21984             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
21985             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
21986             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
21987             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
21988             // and consumes anything.
21989             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
21990             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
21991             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
21992             // identifier and the current token is an arrow.
21993             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
21994                 return parseSimpleArrowFunctionExpression(expr);
21995             }
21996             // Now see if we might be in cases '2' or '3'.
21997             // If the expression was a LHS expression, and we have an assignment operator, then
21998             // we're in '2' or '3'. Consume the assignment and return.
21999             //
22000             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22001             // for cases like `> > =` becoming `>>=`
22002             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22003                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22004             }
22005             // It wasn't an assignment or a lambda.  This is a conditional expression:
22006             return parseConditionalExpressionRest(expr);
22007         }
22008         function isYieldExpression() {
22009             if (token() === 121 /* YieldKeyword */) {
22010                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22011                 // allowed, then definitely parse out a yield expression.
22012                 if (inYieldContext()) {
22013                     return true;
22014                 }
22015                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22016                 // definitely tell that the user was trying to parse a 'yield expr' and not
22017                 // just a normal expr that start with a 'yield' identifier, then parse out
22018                 // a 'yield expr'.  We can then report an error later that they are only
22019                 // allowed in generator expressions.
22020                 //
22021                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22022                 // invocation expression of something called 'yield'.  However, if we have
22023                 // 'yield foo' then that is not legal as a normal expression, so we can
22024                 // definitely recognize this as a yield expression.
22025                 //
22026                 // for now we just check if the next token is an identifier.  More heuristics
22027                 // can be added here later as necessary.  We just need to make sure that we
22028                 // don't accidentally consume something legal.
22029                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22030             }
22031             return false;
22032         }
22033         function nextTokenIsIdentifierOnSameLine() {
22034             nextToken();
22035             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22036         }
22037         function parseYieldExpression() {
22038             var node = createNode(212 /* YieldExpression */);
22039             // YieldExpression[In] :
22040             //      yield
22041             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22042             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22043             nextToken();
22044             if (!scanner.hasPrecedingLineBreak() &&
22045                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22046                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22047                 node.expression = parseAssignmentExpressionOrHigher();
22048                 return finishNode(node);
22049             }
22050             else {
22051                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22052                 // the start of an expression, then this is just a simple "yield" expression.
22053                 return finishNode(node);
22054             }
22055         }
22056         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22057             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22058             var node;
22059             if (asyncModifier) {
22060                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22061                 node.modifiers = asyncModifier;
22062             }
22063             else {
22064                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22065             }
22066             var parameter = createNode(156 /* Parameter */, identifier.pos);
22067             parameter.name = identifier;
22068             finishNode(parameter);
22069             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22070             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22071             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22072             return addJSDocComment(finishNode(node));
22073         }
22074         function tryParseParenthesizedArrowFunctionExpression() {
22075             var triState = isParenthesizedArrowFunctionExpression();
22076             if (triState === 0 /* False */) {
22077                 // It's definitely not a parenthesized arrow function expression.
22078                 return undefined;
22079             }
22080             // If we definitely have an arrow function, then we can just parse one, not requiring a
22081             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22082             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22083             // expression instead.
22084             var arrowFunction = triState === 1 /* True */
22085                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22086                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22087             if (!arrowFunction) {
22088                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22089                 return undefined;
22090             }
22091             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22092             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22093             // have an opening brace, just in case we're in an error state.
22094             var lastToken = token();
22095             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22096             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22097                 ? parseArrowFunctionExpressionBody(isAsync)
22098                 : parseIdentifier();
22099             return finishNode(arrowFunction);
22100         }
22101         //  True        -> We definitely expect a parenthesized arrow function here.
22102         //  False       -> There *cannot* be a parenthesized arrow function here.
22103         //  Unknown     -> There *might* be a parenthesized arrow function here.
22104         //                 Speculatively look ahead to be sure, and rollback if not.
22105         function isParenthesizedArrowFunctionExpression() {
22106             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22107                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22108             }
22109             if (token() === 38 /* EqualsGreaterThanToken */) {
22110                 // ERROR RECOVERY TWEAK:
22111                 // If we see a standalone => try to parse it as an arrow function expression as that's
22112                 // likely what the user intended to write.
22113                 return 1 /* True */;
22114             }
22115             // Definitely not a parenthesized arrow function.
22116             return 0 /* False */;
22117         }
22118         function isParenthesizedArrowFunctionExpressionWorker() {
22119             if (token() === 126 /* AsyncKeyword */) {
22120                 nextToken();
22121                 if (scanner.hasPrecedingLineBreak()) {
22122                     return 0 /* False */;
22123                 }
22124                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22125                     return 0 /* False */;
22126                 }
22127             }
22128             var first = token();
22129             var second = nextToken();
22130             if (first === 20 /* OpenParenToken */) {
22131                 if (second === 21 /* CloseParenToken */) {
22132                     // Simple cases: "() =>", "(): ", and "() {".
22133                     // This is an arrow function with no parameters.
22134                     // The last one is not actually an arrow function,
22135                     // but this is probably what the user intended.
22136                     var third = nextToken();
22137                     switch (third) {
22138                         case 38 /* EqualsGreaterThanToken */:
22139                         case 58 /* ColonToken */:
22140                         case 18 /* OpenBraceToken */:
22141                             return 1 /* True */;
22142                         default:
22143                             return 0 /* False */;
22144                     }
22145                 }
22146                 // If encounter "([" or "({", this could be the start of a binding pattern.
22147                 // Examples:
22148                 //      ([ x ]) => { }
22149                 //      ({ x }) => { }
22150                 //      ([ x ])
22151                 //      ({ x })
22152                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22153                     return 2 /* Unknown */;
22154                 }
22155                 // Simple case: "(..."
22156                 // This is an arrow function with a rest parameter.
22157                 if (second === 25 /* DotDotDotToken */) {
22158                     return 1 /* True */;
22159                 }
22160                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22161                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22162                 // a good error message.
22163                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22164                     return 1 /* True */;
22165                 }
22166                 // If we had "(" followed by something that's not an identifier,
22167                 // then this definitely doesn't look like a lambda.  "this" is not
22168                 // valid, but we want to parse it and then give a semantic error.
22169                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22170                     return 0 /* False */;
22171                 }
22172                 switch (nextToken()) {
22173                     case 58 /* ColonToken */:
22174                         // If we have something like "(a:", then we must have a
22175                         // type-annotated parameter in an arrow function expression.
22176                         return 1 /* True */;
22177                     case 57 /* QuestionToken */:
22178                         nextToken();
22179                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22180                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22181                             return 1 /* True */;
22182                         }
22183                         // Otherwise it is definitely not a lambda.
22184                         return 0 /* False */;
22185                     case 27 /* CommaToken */:
22186                     case 62 /* EqualsToken */:
22187                     case 21 /* CloseParenToken */:
22188                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22189                         return 2 /* Unknown */;
22190                 }
22191                 // It is definitely not an arrow function
22192                 return 0 /* False */;
22193             }
22194             else {
22195                 ts.Debug.assert(first === 29 /* LessThanToken */);
22196                 // If we have "<" not followed by an identifier,
22197                 // then this definitely is not an arrow function.
22198                 if (!isIdentifier()) {
22199                     return 0 /* False */;
22200                 }
22201                 // JSX overrides
22202                 if (sourceFile.languageVariant === 1 /* JSX */) {
22203                     var isArrowFunctionInJsx = lookAhead(function () {
22204                         var third = nextToken();
22205                         if (third === 90 /* ExtendsKeyword */) {
22206                             var fourth = nextToken();
22207                             switch (fourth) {
22208                                 case 62 /* EqualsToken */:
22209                                 case 31 /* GreaterThanToken */:
22210                                     return false;
22211                                 default:
22212                                     return true;
22213                             }
22214                         }
22215                         else if (third === 27 /* CommaToken */) {
22216                             return true;
22217                         }
22218                         return false;
22219                     });
22220                     if (isArrowFunctionInJsx) {
22221                         return 1 /* True */;
22222                     }
22223                     return 0 /* False */;
22224                 }
22225                 // This *could* be a parenthesized arrow function.
22226                 return 2 /* Unknown */;
22227             }
22228         }
22229         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22230             var tokenPos = scanner.getTokenPos();
22231             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22232                 return undefined;
22233             }
22234             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22235             if (!result) {
22236                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22237             }
22238             return result;
22239         }
22240         function tryParseAsyncSimpleArrowFunctionExpression() {
22241             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22242             if (token() === 126 /* AsyncKeyword */) {
22243                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22244                     var asyncModifier = parseModifiersForArrowFunction();
22245                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22246                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22247                 }
22248             }
22249             return undefined;
22250         }
22251         function isUnParenthesizedAsyncArrowFunctionWorker() {
22252             // AsyncArrowFunctionExpression:
22253             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22254             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22255             if (token() === 126 /* AsyncKeyword */) {
22256                 nextToken();
22257                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22258                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22259                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22260                     return 0 /* False */;
22261                 }
22262                 // Check for un-parenthesized AsyncArrowFunction
22263                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22264                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22265                     return 1 /* True */;
22266                 }
22267             }
22268             return 0 /* False */;
22269         }
22270         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22271             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22272             node.modifiers = parseModifiersForArrowFunction();
22273             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22274             // Arrow functions are never generators.
22275             //
22276             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22277             // we have to have a complete parameter list.  Otherwise we might see something like
22278             // a => (b => c)
22279             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22280             // close paren.
22281             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22282                 return undefined;
22283             }
22284             // Parsing a signature isn't enough.
22285             // Parenthesized arrow signatures often look like other valid expressions.
22286             // For instance:
22287             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22288             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22289             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22290             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22291             //
22292             // So we need just a bit of lookahead to ensure that it can only be a signature.
22293             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22294             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22295                 // Returning undefined here will cause our caller to rewind to where we started from.
22296                 return undefined;
22297             }
22298             return node;
22299         }
22300         function parseArrowFunctionExpressionBody(isAsync) {
22301             if (token() === 18 /* OpenBraceToken */) {
22302                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22303             }
22304             if (token() !== 26 /* SemicolonToken */ &&
22305                 token() !== 94 /* FunctionKeyword */ &&
22306                 token() !== 80 /* ClassKeyword */ &&
22307                 isStartOfStatement() &&
22308                 !isStartOfExpressionStatement()) {
22309                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22310                 //
22311                 // Here we try to recover from a potential error situation in the case where the
22312                 // user meant to supply a block. For example, if the user wrote:
22313                 //
22314                 //  a =>
22315                 //      let v = 0;
22316                 //  }
22317                 //
22318                 // they may be missing an open brace.  Check to see if that's the case so we can
22319                 // try to recover better.  If we don't do this, then the next close curly we see may end
22320                 // up preemptively closing the containing construct.
22321                 //
22322                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22323                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22324             }
22325             return isAsync
22326                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22327                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22328         }
22329         function parseConditionalExpressionRest(leftOperand) {
22330             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22331             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22332             if (!questionToken) {
22333                 return leftOperand;
22334             }
22335             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22336             // we do not that for the 'whenFalse' part.
22337             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22338             node.condition = leftOperand;
22339             node.questionToken = questionToken;
22340             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22341             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22342             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22343                 ? parseAssignmentExpressionOrHigher()
22344                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22345             return finishNode(node);
22346         }
22347         function parseBinaryExpressionOrHigher(precedence) {
22348             var leftOperand = parseUnaryExpressionOrHigher();
22349             return parseBinaryExpressionRest(precedence, leftOperand);
22350         }
22351         function isInOrOfKeyword(t) {
22352             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22353         }
22354         function parseBinaryExpressionRest(precedence, leftOperand) {
22355             while (true) {
22356                 // We either have a binary operator here, or we're finished.  We call
22357                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22358                 reScanGreaterToken();
22359                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22360                 // Check the precedence to see if we should "take" this operator
22361                 // - For left associative operator (all operator but **), consume the operator,
22362                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22363                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22364                 //   For example:
22365                 //      a - b - c;
22366                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22367                 //      a * b - c
22368                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22369                 //      a - b * c;
22370                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22371                 // - For right associative operator (**), consume the operator, recursively call the function
22372                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22373                 //   the operator is strictly grater than the current precedence
22374                 //   For example:
22375                 //      a ** b ** c;
22376                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22377                 //      a - b ** c;
22378                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22379                 //      a ** b - c
22380                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22381                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22382                     newPrecedence >= precedence :
22383                     newPrecedence > precedence;
22384                 if (!consumeCurrentOperator) {
22385                     break;
22386                 }
22387                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22388                     break;
22389                 }
22390                 if (token() === 123 /* AsKeyword */) {
22391                     // Make sure we *do* perform ASI for constructs like this:
22392                     //    var x = foo
22393                     //    as (Bar)
22394                     // This should be parsed as an initialized variable, followed
22395                     // by a function call to 'as' with the argument 'Bar'
22396                     if (scanner.hasPrecedingLineBreak()) {
22397                         break;
22398                     }
22399                     else {
22400                         nextToken();
22401                         leftOperand = makeAsExpression(leftOperand, parseType());
22402                     }
22403                 }
22404                 else {
22405                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22406                 }
22407             }
22408             return leftOperand;
22409         }
22410         function isBinaryOperator() {
22411             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22412                 return false;
22413             }
22414             return ts.getBinaryOperatorPrecedence(token()) > 0;
22415         }
22416         function makeBinaryExpression(left, operatorToken, right) {
22417             var node = createNode(209 /* BinaryExpression */, left.pos);
22418             node.left = left;
22419             node.operatorToken = operatorToken;
22420             node.right = right;
22421             return finishNode(node);
22422         }
22423         function makeAsExpression(left, right) {
22424             var node = createNode(217 /* AsExpression */, left.pos);
22425             node.expression = left;
22426             node.type = right;
22427             return finishNode(node);
22428         }
22429         function parsePrefixUnaryExpression() {
22430             var node = createNode(207 /* PrefixUnaryExpression */);
22431             node.operator = token();
22432             nextToken();
22433             node.operand = parseSimpleUnaryExpression();
22434             return finishNode(node);
22435         }
22436         function parseDeleteExpression() {
22437             var node = createNode(203 /* DeleteExpression */);
22438             nextToken();
22439             node.expression = parseSimpleUnaryExpression();
22440             return finishNode(node);
22441         }
22442         function parseTypeOfExpression() {
22443             var node = createNode(204 /* TypeOfExpression */);
22444             nextToken();
22445             node.expression = parseSimpleUnaryExpression();
22446             return finishNode(node);
22447         }
22448         function parseVoidExpression() {
22449             var node = createNode(205 /* VoidExpression */);
22450             nextToken();
22451             node.expression = parseSimpleUnaryExpression();
22452             return finishNode(node);
22453         }
22454         function isAwaitExpression() {
22455             if (token() === 127 /* AwaitKeyword */) {
22456                 if (inAwaitContext()) {
22457                     return true;
22458                 }
22459                 // here we are using similar heuristics as 'isYieldExpression'
22460                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22461             }
22462             return false;
22463         }
22464         function parseAwaitExpression() {
22465             var node = createNode(206 /* AwaitExpression */);
22466             nextToken();
22467             node.expression = parseSimpleUnaryExpression();
22468             return finishNode(node);
22469         }
22470         /**
22471          * Parse ES7 exponential expression and await expression
22472          *
22473          * ES7 ExponentiationExpression:
22474          *      1) UnaryExpression[?Yield]
22475          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22476          *
22477          */
22478         function parseUnaryExpressionOrHigher() {
22479             /**
22480              * ES7 UpdateExpression:
22481              *      1) LeftHandSideExpression[?Yield]
22482              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22483              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22484              *      4) ++UnaryExpression[?Yield]
22485              *      5) --UnaryExpression[?Yield]
22486              */
22487             if (isUpdateExpression()) {
22488                 var updateExpression = parseUpdateExpression();
22489                 return token() === 42 /* AsteriskAsteriskToken */ ?
22490                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22491                     updateExpression;
22492             }
22493             /**
22494              * ES7 UnaryExpression:
22495              *      1) UpdateExpression[?yield]
22496              *      2) delete UpdateExpression[?yield]
22497              *      3) void UpdateExpression[?yield]
22498              *      4) typeof UpdateExpression[?yield]
22499              *      5) + UpdateExpression[?yield]
22500              *      6) - UpdateExpression[?yield]
22501              *      7) ~ UpdateExpression[?yield]
22502              *      8) ! UpdateExpression[?yield]
22503              */
22504             var unaryOperator = token();
22505             var simpleUnaryExpression = parseSimpleUnaryExpression();
22506             if (token() === 42 /* AsteriskAsteriskToken */) {
22507                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22508                 var end = simpleUnaryExpression.end;
22509                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22510                     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);
22511                 }
22512                 else {
22513                     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));
22514                 }
22515             }
22516             return simpleUnaryExpression;
22517         }
22518         /**
22519          * Parse ES7 simple-unary expression or higher:
22520          *
22521          * ES7 UnaryExpression:
22522          *      1) UpdateExpression[?yield]
22523          *      2) delete UnaryExpression[?yield]
22524          *      3) void UnaryExpression[?yield]
22525          *      4) typeof UnaryExpression[?yield]
22526          *      5) + UnaryExpression[?yield]
22527          *      6) - UnaryExpression[?yield]
22528          *      7) ~ UnaryExpression[?yield]
22529          *      8) ! UnaryExpression[?yield]
22530          *      9) [+Await] await UnaryExpression[?yield]
22531          */
22532         function parseSimpleUnaryExpression() {
22533             switch (token()) {
22534                 case 39 /* PlusToken */:
22535                 case 40 /* MinusToken */:
22536                 case 54 /* TildeToken */:
22537                 case 53 /* ExclamationToken */:
22538                     return parsePrefixUnaryExpression();
22539                 case 85 /* DeleteKeyword */:
22540                     return parseDeleteExpression();
22541                 case 108 /* TypeOfKeyword */:
22542                     return parseTypeOfExpression();
22543                 case 110 /* VoidKeyword */:
22544                     return parseVoidExpression();
22545                 case 29 /* LessThanToken */:
22546                     // This is modified UnaryExpression grammar in TypeScript
22547                     //  UnaryExpression (modified):
22548                     //      < type > UnaryExpression
22549                     return parseTypeAssertion();
22550                 case 127 /* AwaitKeyword */:
22551                     if (isAwaitExpression()) {
22552                         return parseAwaitExpression();
22553                     }
22554                 // falls through
22555                 default:
22556                     return parseUpdateExpression();
22557             }
22558         }
22559         /**
22560          * Check if the current token can possibly be an ES7 increment expression.
22561          *
22562          * ES7 UpdateExpression:
22563          *      LeftHandSideExpression[?Yield]
22564          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22565          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22566          *      ++LeftHandSideExpression[?Yield]
22567          *      --LeftHandSideExpression[?Yield]
22568          */
22569         function isUpdateExpression() {
22570             // This function is called inside parseUnaryExpression to decide
22571             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22572             switch (token()) {
22573                 case 39 /* PlusToken */:
22574                 case 40 /* MinusToken */:
22575                 case 54 /* TildeToken */:
22576                 case 53 /* ExclamationToken */:
22577                 case 85 /* DeleteKeyword */:
22578                 case 108 /* TypeOfKeyword */:
22579                 case 110 /* VoidKeyword */:
22580                 case 127 /* AwaitKeyword */:
22581                     return false;
22582                 case 29 /* LessThanToken */:
22583                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22584                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22585                         return false;
22586                     }
22587                 // We are in JSX context and the token is part of JSXElement.
22588                 // falls through
22589                 default:
22590                     return true;
22591             }
22592         }
22593         /**
22594          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22595          *
22596          * ES7 UpdateExpression[yield]:
22597          *      1) LeftHandSideExpression[?yield]
22598          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22599          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22600          *      4) ++LeftHandSideExpression[?yield]
22601          *      5) --LeftHandSideExpression[?yield]
22602          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22603          */
22604         function parseUpdateExpression() {
22605             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22606                 var node = createNode(207 /* PrefixUnaryExpression */);
22607                 node.operator = token();
22608                 nextToken();
22609                 node.operand = parseLeftHandSideExpressionOrHigher();
22610                 return finishNode(node);
22611             }
22612             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22613                 // JSXElement is part of primaryExpression
22614                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22615             }
22616             var expression = parseLeftHandSideExpressionOrHigher();
22617             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22618             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22619                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22620                 node.operand = expression;
22621                 node.operator = token();
22622                 nextToken();
22623                 return finishNode(node);
22624             }
22625             return expression;
22626         }
22627         function parseLeftHandSideExpressionOrHigher() {
22628             // Original Ecma:
22629             // LeftHandSideExpression: See 11.2
22630             //      NewExpression
22631             //      CallExpression
22632             //
22633             // Our simplification:
22634             //
22635             // LeftHandSideExpression: See 11.2
22636             //      MemberExpression
22637             //      CallExpression
22638             //
22639             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22640             // MemberExpression to make our lives easier.
22641             //
22642             // to best understand the below code, it's important to see how CallExpression expands
22643             // out into its own productions:
22644             //
22645             // CallExpression:
22646             //      MemberExpression Arguments
22647             //      CallExpression Arguments
22648             //      CallExpression[Expression]
22649             //      CallExpression.IdentifierName
22650             //      import (AssignmentExpression)
22651             //      super Arguments
22652             //      super.IdentifierName
22653             //
22654             // Because of the recursion in these calls, we need to bottom out first. There are three
22655             // bottom out states we can run into: 1) We see 'super' which must start either of
22656             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22657             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22658             // or starts the beginning of the first four CallExpression productions.
22659             var expression;
22660             if (token() === 96 /* ImportKeyword */) {
22661                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22662                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22663                     // For example:
22664                     //      var foo3 = require("subfolder
22665                     //      import * as foo1 from "module-from-node
22666                     // We want this import to be a statement rather than import call expression
22667                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22668                     expression = parseTokenNode();
22669                 }
22670                 else if (lookAhead(nextTokenIsDot)) {
22671                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22672                     var fullStart = scanner.getStartPos();
22673                     nextToken(); // advance past the 'import'
22674                     nextToken(); // advance past the dot
22675                     var node = createNode(219 /* MetaProperty */, fullStart);
22676                     node.keywordToken = 96 /* ImportKeyword */;
22677                     node.name = parseIdentifierName();
22678                     expression = finishNode(node);
22679                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22680                 }
22681                 else {
22682                     expression = parseMemberExpressionOrHigher();
22683                 }
22684             }
22685             else {
22686                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22687             }
22688             // Now, we *may* be complete.  However, we might have consumed the start of a
22689             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22690             // of it here to be complete.
22691             return parseCallExpressionRest(expression);
22692         }
22693         function parseMemberExpressionOrHigher() {
22694             // Note: to make our lives simpler, we decompose the NewExpression productions and
22695             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22696             // like so:
22697             //
22698             //   PrimaryExpression : See 11.1
22699             //      this
22700             //      Identifier
22701             //      Literal
22702             //      ArrayLiteral
22703             //      ObjectLiteral
22704             //      (Expression)
22705             //      FunctionExpression
22706             //      new MemberExpression Arguments?
22707             //
22708             //   MemberExpression : See 11.2
22709             //      PrimaryExpression
22710             //      MemberExpression[Expression]
22711             //      MemberExpression.IdentifierName
22712             //
22713             //   CallExpression : See 11.2
22714             //      MemberExpression
22715             //      CallExpression Arguments
22716             //      CallExpression[Expression]
22717             //      CallExpression.IdentifierName
22718             //
22719             // Technically this is ambiguous.  i.e. CallExpression defines:
22720             //
22721             //   CallExpression:
22722             //      CallExpression Arguments
22723             //
22724             // If you see: "new Foo()"
22725             //
22726             // Then that could be treated as a single ObjectCreationExpression, or it could be
22727             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22728             // the original grammar) by making sure that if we see an ObjectCreationExpression
22729             // we always consume arguments if they are there. So we treat "new Foo()" as an
22730             // object creation only, and not at all as an invocation.  Another way to think
22731             // about this is that for every "new" that we see, we will consume an argument list if
22732             // it is there as part of the *associated* object creation node.  Any additional
22733             // argument lists we see, will become invocation expressions.
22734             //
22735             // Because there are no other places in the grammar now that refer to FunctionExpression
22736             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22737             // production.
22738             //
22739             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22740             // of the recursion immediately.  So we parse out a primary expression to start with.
22741             var expression = parsePrimaryExpression();
22742             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22743         }
22744         function parseSuperExpression() {
22745             var expression = parseTokenNode();
22746             if (token() === 29 /* LessThanToken */) {
22747                 var startPos = getNodePos();
22748                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22749                 if (typeArguments !== undefined) {
22750                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22751                 }
22752             }
22753             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22754                 return expression;
22755             }
22756             // If we have seen "super" it must be followed by '(' or '.'.
22757             // If it wasn't then just try to parse out a '.' and report an error.
22758             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22759             node.expression = expression;
22760             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22761             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22762             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22763             return finishNode(node);
22764         }
22765         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22766             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22767             var result;
22768             if (opening.kind === 268 /* JsxOpeningElement */) {
22769                 var node = createNode(266 /* JsxElement */, opening.pos);
22770                 node.openingElement = opening;
22771                 node.children = parseJsxChildren(node.openingElement);
22772                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22773                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22774                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22775                 }
22776                 result = finishNode(node);
22777             }
22778             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22779                 var node = createNode(270 /* JsxFragment */, opening.pos);
22780                 node.openingFragment = opening;
22781                 node.children = parseJsxChildren(node.openingFragment);
22782                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22783                 result = finishNode(node);
22784             }
22785             else {
22786                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22787                 // Nothing else to do for self-closing elements
22788                 result = opening;
22789             }
22790             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22791             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22792             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22793             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22794             // does less damage and we can report a better error.
22795             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22796             // of one sort or another.
22797             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22798                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22799                 if (invalidElement) {
22800                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22801                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22802                     badNode.end = invalidElement.end;
22803                     badNode.left = result;
22804                     badNode.right = invalidElement;
22805                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22806                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22807                     return badNode;
22808                 }
22809             }
22810             return result;
22811         }
22812         function parseJsxText() {
22813             var node = createNode(11 /* JsxText */);
22814             node.text = scanner.getTokenValue();
22815             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22816             currentToken = scanner.scanJsxToken();
22817             return finishNode(node);
22818         }
22819         function parseJsxChild(openingTag, token) {
22820             switch (token) {
22821                 case 1 /* EndOfFileToken */:
22822                     // If we hit EOF, issue the error at the tag that lacks the closing element
22823                     // rather than at the end of the file (which is useless)
22824                     if (ts.isJsxOpeningFragment(openingTag)) {
22825                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22826                     }
22827                     else {
22828                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22829                         // or to cover only 'Foo' in < Foo >
22830                         var tag = openingTag.tagName;
22831                         var start = ts.skipTrivia(sourceText, tag.pos);
22832                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22833                     }
22834                     return undefined;
22835                 case 30 /* LessThanSlashToken */:
22836                 case 7 /* ConflictMarkerTrivia */:
22837                     return undefined;
22838                 case 11 /* JsxText */:
22839                 case 12 /* JsxTextAllWhiteSpaces */:
22840                     return parseJsxText();
22841                 case 18 /* OpenBraceToken */:
22842                     return parseJsxExpression(/*inExpressionContext*/ false);
22843                 case 29 /* LessThanToken */:
22844                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
22845                 default:
22846                     return ts.Debug.assertNever(token);
22847             }
22848         }
22849         function parseJsxChildren(openingTag) {
22850             var list = [];
22851             var listPos = getNodePos();
22852             var saveParsingContext = parsingContext;
22853             parsingContext |= 1 << 14 /* JsxChildren */;
22854             while (true) {
22855                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
22856                 if (!child)
22857                     break;
22858                 list.push(child);
22859             }
22860             parsingContext = saveParsingContext;
22861             return createNodeArray(list, listPos);
22862         }
22863         function parseJsxAttributes() {
22864             var jsxAttributes = createNode(274 /* JsxAttributes */);
22865             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
22866             return finishNode(jsxAttributes);
22867         }
22868         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
22869             var fullStart = scanner.getStartPos();
22870             parseExpected(29 /* LessThanToken */);
22871             if (token() === 31 /* GreaterThanToken */) {
22872                 // See below for explanation of scanJsxText
22873                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
22874                 scanJsxText();
22875                 return finishNode(node_1);
22876             }
22877             var tagName = parseJsxElementName();
22878             var typeArguments = tryParseTypeArguments();
22879             var attributes = parseJsxAttributes();
22880             var node;
22881             if (token() === 31 /* GreaterThanToken */) {
22882                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
22883                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
22884                 // scanning errors
22885                 node = createNode(268 /* JsxOpeningElement */, fullStart);
22886                 scanJsxText();
22887             }
22888             else {
22889                 parseExpected(43 /* SlashToken */);
22890                 if (inExpressionContext) {
22891                     parseExpected(31 /* GreaterThanToken */);
22892                 }
22893                 else {
22894                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22895                     scanJsxText();
22896                 }
22897                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
22898             }
22899             node.tagName = tagName;
22900             node.typeArguments = typeArguments;
22901             node.attributes = attributes;
22902             return finishNode(node);
22903         }
22904         function parseJsxElementName() {
22905             scanJsxIdentifier();
22906             // JsxElement can have name in the form of
22907             //      propertyAccessExpression
22908             //      primaryExpression in the form of an identifier and "this" keyword
22909             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
22910             // We only want to consider "this" as a primaryExpression
22911             var expression = token() === 104 /* ThisKeyword */ ?
22912                 parseTokenNode() : parseIdentifierName();
22913             while (parseOptional(24 /* DotToken */)) {
22914                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
22915                 propertyAccess.expression = expression;
22916                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
22917                 expression = finishNode(propertyAccess);
22918             }
22919             return expression;
22920         }
22921         function parseJsxExpression(inExpressionContext) {
22922             var node = createNode(276 /* JsxExpression */);
22923             if (!parseExpected(18 /* OpenBraceToken */)) {
22924                 return undefined;
22925             }
22926             if (token() !== 19 /* CloseBraceToken */) {
22927                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
22928                 // Only an AssignmentExpression is valid here per the JSX spec,
22929                 // but we can unambiguously parse a comma sequence and provide
22930                 // a better error message in grammar checking.
22931                 node.expression = parseExpression();
22932             }
22933             if (inExpressionContext) {
22934                 parseExpected(19 /* CloseBraceToken */);
22935             }
22936             else {
22937                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
22938                     scanJsxText();
22939                 }
22940             }
22941             return finishNode(node);
22942         }
22943         function parseJsxAttribute() {
22944             if (token() === 18 /* OpenBraceToken */) {
22945                 return parseJsxSpreadAttribute();
22946             }
22947             scanJsxIdentifier();
22948             var node = createNode(273 /* JsxAttribute */);
22949             node.name = parseIdentifierName();
22950             if (token() === 62 /* EqualsToken */) {
22951                 switch (scanJsxAttributeValue()) {
22952                     case 10 /* StringLiteral */:
22953                         node.initializer = parseLiteralNode();
22954                         break;
22955                     default:
22956                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
22957                         break;
22958                 }
22959             }
22960             return finishNode(node);
22961         }
22962         function parseJsxSpreadAttribute() {
22963             var node = createNode(275 /* JsxSpreadAttribute */);
22964             parseExpected(18 /* OpenBraceToken */);
22965             parseExpected(25 /* DotDotDotToken */);
22966             node.expression = parseExpression();
22967             parseExpected(19 /* CloseBraceToken */);
22968             return finishNode(node);
22969         }
22970         function parseJsxClosingElement(inExpressionContext) {
22971             var node = createNode(269 /* JsxClosingElement */);
22972             parseExpected(30 /* LessThanSlashToken */);
22973             node.tagName = parseJsxElementName();
22974             if (inExpressionContext) {
22975                 parseExpected(31 /* GreaterThanToken */);
22976             }
22977             else {
22978                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22979                 scanJsxText();
22980             }
22981             return finishNode(node);
22982         }
22983         function parseJsxClosingFragment(inExpressionContext) {
22984             var node = createNode(272 /* JsxClosingFragment */);
22985             parseExpected(30 /* LessThanSlashToken */);
22986             if (ts.tokenIsIdentifierOrKeyword(token())) {
22987                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
22988             }
22989             if (inExpressionContext) {
22990                 parseExpected(31 /* GreaterThanToken */);
22991             }
22992             else {
22993                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22994                 scanJsxText();
22995             }
22996             return finishNode(node);
22997         }
22998         function parseTypeAssertion() {
22999             var node = createNode(199 /* TypeAssertionExpression */);
23000             parseExpected(29 /* LessThanToken */);
23001             node.type = parseType();
23002             parseExpected(31 /* GreaterThanToken */);
23003             node.expression = parseSimpleUnaryExpression();
23004             return finishNode(node);
23005         }
23006         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23007             nextToken();
23008             return ts.tokenIsIdentifierOrKeyword(token())
23009                 || token() === 22 /* OpenBracketToken */
23010                 || isTemplateStartOfTaggedTemplate();
23011         }
23012         function isStartOfOptionalPropertyOrElementAccessChain() {
23013             return token() === 28 /* QuestionDotToken */
23014                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23015         }
23016         function tryReparseOptionalChain(node) {
23017             if (node.flags & 32 /* OptionalChain */) {
23018                 return true;
23019             }
23020             // check for an optional chain in a non-null expression
23021             if (ts.isNonNullExpression(node)) {
23022                 var expr = node.expression;
23023                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23024                     expr = expr.expression;
23025                 }
23026                 if (expr.flags & 32 /* OptionalChain */) {
23027                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23028                     while (ts.isNonNullExpression(node)) {
23029                         node.flags |= 32 /* OptionalChain */;
23030                         node = node.expression;
23031                     }
23032                     return true;
23033                 }
23034             }
23035             return false;
23036         }
23037         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23038             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23039             propertyAccess.expression = expression;
23040             propertyAccess.questionDotToken = questionDotToken;
23041             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23042             if (questionDotToken || tryReparseOptionalChain(expression)) {
23043                 propertyAccess.flags |= 32 /* OptionalChain */;
23044                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23045                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23046                 }
23047             }
23048             return finishNode(propertyAccess);
23049         }
23050         function parseElementAccessExpressionRest(expression, questionDotToken) {
23051             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23052             indexedAccess.expression = expression;
23053             indexedAccess.questionDotToken = questionDotToken;
23054             if (token() === 23 /* CloseBracketToken */) {
23055                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23056             }
23057             else {
23058                 var argument = allowInAnd(parseExpression);
23059                 if (ts.isStringOrNumericLiteralLike(argument)) {
23060                     argument.text = internIdentifier(argument.text);
23061                 }
23062                 indexedAccess.argumentExpression = argument;
23063             }
23064             parseExpected(23 /* CloseBracketToken */);
23065             if (questionDotToken || tryReparseOptionalChain(expression)) {
23066                 indexedAccess.flags |= 32 /* OptionalChain */;
23067             }
23068             return finishNode(indexedAccess);
23069         }
23070         function parseMemberExpressionRest(expression, allowOptionalChain) {
23071             while (true) {
23072                 var questionDotToken = void 0;
23073                 var isPropertyAccess = false;
23074                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23075                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23076                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23077                 }
23078                 else {
23079                     isPropertyAccess = parseOptional(24 /* DotToken */);
23080                 }
23081                 if (isPropertyAccess) {
23082                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23083                     continue;
23084                 }
23085                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23086                     nextToken();
23087                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23088                     nonNullExpression.expression = expression;
23089                     expression = finishNode(nonNullExpression);
23090                     continue;
23091                 }
23092                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23093                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23094                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23095                     continue;
23096                 }
23097                 if (isTemplateStartOfTaggedTemplate()) {
23098                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23099                     continue;
23100                 }
23101                 return expression;
23102             }
23103         }
23104         function isTemplateStartOfTaggedTemplate() {
23105             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23106         }
23107         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23108             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23109             tagExpression.tag = tag;
23110             tagExpression.questionDotToken = questionDotToken;
23111             tagExpression.typeArguments = typeArguments;
23112             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23113                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23114                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23115             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23116                 tagExpression.flags |= 32 /* OptionalChain */;
23117             }
23118             return finishNode(tagExpression);
23119         }
23120         function parseCallExpressionRest(expression) {
23121             while (true) {
23122                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23123                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23124                 // handle 'foo<<T>()'
23125                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23126                     // See if this is the start of a generic invocation.  If so, consume it and
23127                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23128                     // part of an arithmetic expression.  Break out so we consume it higher in the
23129                     // stack.
23130                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23131                     if (typeArguments) {
23132                         if (isTemplateStartOfTaggedTemplate()) {
23133                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23134                             continue;
23135                         }
23136                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23137                         callExpr.expression = expression;
23138                         callExpr.questionDotToken = questionDotToken;
23139                         callExpr.typeArguments = typeArguments;
23140                         callExpr.arguments = parseArgumentList();
23141                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23142                             callExpr.flags |= 32 /* OptionalChain */;
23143                         }
23144                         expression = finishNode(callExpr);
23145                         continue;
23146                     }
23147                 }
23148                 else if (token() === 20 /* OpenParenToken */) {
23149                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23150                     callExpr.expression = expression;
23151                     callExpr.questionDotToken = questionDotToken;
23152                     callExpr.arguments = parseArgumentList();
23153                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23154                         callExpr.flags |= 32 /* OptionalChain */;
23155                     }
23156                     expression = finishNode(callExpr);
23157                     continue;
23158                 }
23159                 if (questionDotToken) {
23160                     // We failed to parse anything, so report a missing identifier here.
23161                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23162                     propertyAccess.expression = expression;
23163                     propertyAccess.questionDotToken = questionDotToken;
23164                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23165                     propertyAccess.flags |= 32 /* OptionalChain */;
23166                     expression = finishNode(propertyAccess);
23167                 }
23168                 break;
23169             }
23170             return expression;
23171         }
23172         function parseArgumentList() {
23173             parseExpected(20 /* OpenParenToken */);
23174             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23175             parseExpected(21 /* CloseParenToken */);
23176             return result;
23177         }
23178         function parseTypeArgumentsInExpression() {
23179             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23180                 return undefined;
23181             }
23182             nextToken();
23183             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23184             if (!parseExpected(31 /* GreaterThanToken */)) {
23185                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23186                 return undefined;
23187             }
23188             // If we have a '<', then only parse this as a argument list if the type arguments
23189             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23190             return typeArguments && canFollowTypeArgumentsInExpression()
23191                 ? typeArguments
23192                 : undefined;
23193         }
23194         function canFollowTypeArgumentsInExpression() {
23195             switch (token()) {
23196                 case 20 /* OpenParenToken */: // foo<x>(
23197                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23198                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23199                 // these are the only tokens can legally follow a type argument
23200                 // list. So we definitely want to treat them as type arg lists.
23201                 // falls through
23202                 case 24 /* DotToken */: // foo<x>.
23203                 case 21 /* CloseParenToken */: // foo<x>)
23204                 case 23 /* CloseBracketToken */: // foo<x>]
23205                 case 58 /* ColonToken */: // foo<x>:
23206                 case 26 /* SemicolonToken */: // foo<x>;
23207                 case 57 /* QuestionToken */: // foo<x>?
23208                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23209                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23210                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23211                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23212                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23213                 case 56 /* BarBarToken */: // foo<x> ||
23214                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23215                 case 52 /* CaretToken */: // foo<x> ^
23216                 case 50 /* AmpersandToken */: // foo<x> &
23217                 case 51 /* BarToken */: // foo<x> |
23218                 case 19 /* CloseBraceToken */: // foo<x> }
23219                 case 1 /* EndOfFileToken */: // foo<x>
23220                     // these cases can't legally follow a type arg list.  However, they're not legal
23221                     // expressions either.  The user is probably in the middle of a generic type. So
23222                     // treat it as such.
23223                     return true;
23224                 case 27 /* CommaToken */: // foo<x>,
23225                 case 18 /* OpenBraceToken */: // foo<x> {
23226                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23227                 // as an invocation expression.  Instead, we want to parse out the expression
23228                 // in isolation from the type arguments.
23229                 // falls through
23230                 default:
23231                     // Anything else treat as an expression.
23232                     return false;
23233             }
23234         }
23235         function parsePrimaryExpression() {
23236             switch (token()) {
23237                 case 8 /* NumericLiteral */:
23238                 case 9 /* BigIntLiteral */:
23239                 case 10 /* StringLiteral */:
23240                 case 14 /* NoSubstitutionTemplateLiteral */:
23241                     return parseLiteralNode();
23242                 case 104 /* ThisKeyword */:
23243                 case 102 /* SuperKeyword */:
23244                 case 100 /* NullKeyword */:
23245                 case 106 /* TrueKeyword */:
23246                 case 91 /* FalseKeyword */:
23247                     return parseTokenNode();
23248                 case 20 /* OpenParenToken */:
23249                     return parseParenthesizedExpression();
23250                 case 22 /* OpenBracketToken */:
23251                     return parseArrayLiteralExpression();
23252                 case 18 /* OpenBraceToken */:
23253                     return parseObjectLiteralExpression();
23254                 case 126 /* AsyncKeyword */:
23255                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23256                     // If we encounter `async [no LineTerminator here] function` then this is an async
23257                     // function; otherwise, its an identifier.
23258                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23259                         break;
23260                     }
23261                     return parseFunctionExpression();
23262                 case 80 /* ClassKeyword */:
23263                     return parseClassExpression();
23264                 case 94 /* FunctionKeyword */:
23265                     return parseFunctionExpression();
23266                 case 99 /* NewKeyword */:
23267                     return parseNewExpressionOrNewDotTarget();
23268                 case 43 /* SlashToken */:
23269                 case 67 /* SlashEqualsToken */:
23270                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23271                         return parseLiteralNode();
23272                     }
23273                     break;
23274                 case 15 /* TemplateHead */:
23275                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23276             }
23277             return parseIdentifier(ts.Diagnostics.Expression_expected);
23278         }
23279         function parseParenthesizedExpression() {
23280             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23281             parseExpected(20 /* OpenParenToken */);
23282             node.expression = allowInAnd(parseExpression);
23283             parseExpected(21 /* CloseParenToken */);
23284             return finishNode(node);
23285         }
23286         function parseSpreadElement() {
23287             var node = createNode(213 /* SpreadElement */);
23288             parseExpected(25 /* DotDotDotToken */);
23289             node.expression = parseAssignmentExpressionOrHigher();
23290             return finishNode(node);
23291         }
23292         function parseArgumentOrArrayLiteralElement() {
23293             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23294                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23295                     parseAssignmentExpressionOrHigher();
23296         }
23297         function parseArgumentExpression() {
23298             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23299         }
23300         function parseArrayLiteralExpression() {
23301             var node = createNode(192 /* ArrayLiteralExpression */);
23302             parseExpected(22 /* OpenBracketToken */);
23303             if (scanner.hasPrecedingLineBreak()) {
23304                 node.multiLine = true;
23305             }
23306             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23307             parseExpected(23 /* CloseBracketToken */);
23308             return finishNode(node);
23309         }
23310         function parseObjectLiteralElement() {
23311             var node = createNodeWithJSDoc(0 /* Unknown */);
23312             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23313                 node.kind = 283 /* SpreadAssignment */;
23314                 node.expression = parseAssignmentExpressionOrHigher();
23315                 return finishNode(node);
23316             }
23317             node.decorators = parseDecorators();
23318             node.modifiers = parseModifiers();
23319             if (parseContextualModifier(131 /* GetKeyword */)) {
23320                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23321             }
23322             if (parseContextualModifier(142 /* SetKeyword */)) {
23323                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23324             }
23325             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23326             var tokenIsIdentifier = isIdentifier();
23327             node.name = parsePropertyName();
23328             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23329             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23330             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23331             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23332                 return parseMethodDeclaration(node, asteriskToken);
23333             }
23334             // check if it is short-hand property assignment or normal property assignment
23335             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23336             // CoverInitializedName[Yield] :
23337             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23338             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23339             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23340             if (isShorthandPropertyAssignment) {
23341                 node.kind = 282 /* ShorthandPropertyAssignment */;
23342                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23343                 if (equalsToken) {
23344                     node.equalsToken = equalsToken;
23345                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23346                 }
23347             }
23348             else {
23349                 node.kind = 281 /* PropertyAssignment */;
23350                 parseExpected(58 /* ColonToken */);
23351                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23352             }
23353             return finishNode(node);
23354         }
23355         function parseObjectLiteralExpression() {
23356             var node = createNode(193 /* ObjectLiteralExpression */);
23357             var openBracePosition = scanner.getTokenPos();
23358             parseExpected(18 /* OpenBraceToken */);
23359             if (scanner.hasPrecedingLineBreak()) {
23360                 node.multiLine = true;
23361             }
23362             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23363             if (!parseExpected(19 /* CloseBraceToken */)) {
23364                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23365                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23366                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23367                 }
23368             }
23369             return finishNode(node);
23370         }
23371         function parseFunctionExpression() {
23372             // GeneratorExpression:
23373             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23374             //
23375             // FunctionExpression:
23376             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23377             var saveDecoratorContext = inDecoratorContext();
23378             if (saveDecoratorContext) {
23379                 setDecoratorContext(/*val*/ false);
23380             }
23381             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23382             node.modifiers = parseModifiers();
23383             parseExpected(94 /* FunctionKeyword */);
23384             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23385             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23386             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23387             node.name =
23388                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23389                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23390                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23391                             parseOptionalIdentifier();
23392             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23393             node.body = parseFunctionBlock(isGenerator | isAsync);
23394             if (saveDecoratorContext) {
23395                 setDecoratorContext(/*val*/ true);
23396             }
23397             return finishNode(node);
23398         }
23399         function parseOptionalIdentifier() {
23400             return isIdentifier() ? parseIdentifier() : undefined;
23401         }
23402         function parseNewExpressionOrNewDotTarget() {
23403             var fullStart = scanner.getStartPos();
23404             parseExpected(99 /* NewKeyword */);
23405             if (parseOptional(24 /* DotToken */)) {
23406                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23407                 node_2.keywordToken = 99 /* NewKeyword */;
23408                 node_2.name = parseIdentifierName();
23409                 return finishNode(node_2);
23410             }
23411             var expression = parsePrimaryExpression();
23412             var typeArguments;
23413             while (true) {
23414                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23415                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23416                 if (isTemplateStartOfTaggedTemplate()) {
23417                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23418                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23419                     typeArguments = undefined;
23420                 }
23421                 break;
23422             }
23423             var node = createNode(197 /* NewExpression */, fullStart);
23424             node.expression = expression;
23425             node.typeArguments = typeArguments;
23426             if (token() === 20 /* OpenParenToken */) {
23427                 node.arguments = parseArgumentList();
23428             }
23429             else if (node.typeArguments) {
23430                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23431             }
23432             return finishNode(node);
23433         }
23434         // STATEMENTS
23435         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23436             var node = createNode(223 /* Block */);
23437             var openBracePosition = scanner.getTokenPos();
23438             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23439                 if (scanner.hasPrecedingLineBreak()) {
23440                     node.multiLine = true;
23441                 }
23442                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23443                 if (!parseExpected(19 /* CloseBraceToken */)) {
23444                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23445                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23446                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23447                     }
23448                 }
23449             }
23450             else {
23451                 node.statements = createMissingList();
23452             }
23453             return finishNode(node);
23454         }
23455         function parseFunctionBlock(flags, diagnosticMessage) {
23456             var savedYieldContext = inYieldContext();
23457             setYieldContext(!!(flags & 1 /* Yield */));
23458             var savedAwaitContext = inAwaitContext();
23459             setAwaitContext(!!(flags & 2 /* Await */));
23460             // We may be in a [Decorator] context when parsing a function expression or
23461             // arrow function. The body of the function is not in [Decorator] context.
23462             var saveDecoratorContext = inDecoratorContext();
23463             if (saveDecoratorContext) {
23464                 setDecoratorContext(/*val*/ false);
23465             }
23466             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23467             if (saveDecoratorContext) {
23468                 setDecoratorContext(/*val*/ true);
23469             }
23470             setYieldContext(savedYieldContext);
23471             setAwaitContext(savedAwaitContext);
23472             return block;
23473         }
23474         function parseEmptyStatement() {
23475             var node = createNode(224 /* EmptyStatement */);
23476             parseExpected(26 /* SemicolonToken */);
23477             return finishNode(node);
23478         }
23479         function parseIfStatement() {
23480             var node = createNode(227 /* IfStatement */);
23481             parseExpected(95 /* IfKeyword */);
23482             parseExpected(20 /* OpenParenToken */);
23483             node.expression = allowInAnd(parseExpression);
23484             parseExpected(21 /* CloseParenToken */);
23485             node.thenStatement = parseStatement();
23486             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23487             return finishNode(node);
23488         }
23489         function parseDoStatement() {
23490             var node = createNode(228 /* DoStatement */);
23491             parseExpected(86 /* DoKeyword */);
23492             node.statement = parseStatement();
23493             parseExpected(111 /* WhileKeyword */);
23494             parseExpected(20 /* OpenParenToken */);
23495             node.expression = allowInAnd(parseExpression);
23496             parseExpected(21 /* CloseParenToken */);
23497             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23498             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23499             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23500             //  do;while(0)x will have a semicolon inserted before x.
23501             parseOptional(26 /* SemicolonToken */);
23502             return finishNode(node);
23503         }
23504         function parseWhileStatement() {
23505             var node = createNode(229 /* WhileStatement */);
23506             parseExpected(111 /* WhileKeyword */);
23507             parseExpected(20 /* OpenParenToken */);
23508             node.expression = allowInAnd(parseExpression);
23509             parseExpected(21 /* CloseParenToken */);
23510             node.statement = parseStatement();
23511             return finishNode(node);
23512         }
23513         function parseForOrForInOrForOfStatement() {
23514             var pos = getNodePos();
23515             parseExpected(93 /* ForKeyword */);
23516             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23517             parseExpected(20 /* OpenParenToken */);
23518             var initializer;
23519             if (token() !== 26 /* SemicolonToken */) {
23520                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23521                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23522                 }
23523                 else {
23524                     initializer = disallowInAnd(parseExpression);
23525                 }
23526             }
23527             var forOrForInOrForOfStatement;
23528             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23529                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23530                 forOfStatement.awaitModifier = awaitToken;
23531                 forOfStatement.initializer = initializer;
23532                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23533                 parseExpected(21 /* CloseParenToken */);
23534                 forOrForInOrForOfStatement = forOfStatement;
23535             }
23536             else if (parseOptional(97 /* InKeyword */)) {
23537                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23538                 forInStatement.initializer = initializer;
23539                 forInStatement.expression = allowInAnd(parseExpression);
23540                 parseExpected(21 /* CloseParenToken */);
23541                 forOrForInOrForOfStatement = forInStatement;
23542             }
23543             else {
23544                 var forStatement = createNode(230 /* ForStatement */, pos);
23545                 forStatement.initializer = initializer;
23546                 parseExpected(26 /* SemicolonToken */);
23547                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23548                     forStatement.condition = allowInAnd(parseExpression);
23549                 }
23550                 parseExpected(26 /* SemicolonToken */);
23551                 if (token() !== 21 /* CloseParenToken */) {
23552                     forStatement.incrementor = allowInAnd(parseExpression);
23553                 }
23554                 parseExpected(21 /* CloseParenToken */);
23555                 forOrForInOrForOfStatement = forStatement;
23556             }
23557             forOrForInOrForOfStatement.statement = parseStatement();
23558             return finishNode(forOrForInOrForOfStatement);
23559         }
23560         function parseBreakOrContinueStatement(kind) {
23561             var node = createNode(kind);
23562             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23563             if (!canParseSemicolon()) {
23564                 node.label = parseIdentifier();
23565             }
23566             parseSemicolon();
23567             return finishNode(node);
23568         }
23569         function parseReturnStatement() {
23570             var node = createNode(235 /* ReturnStatement */);
23571             parseExpected(101 /* ReturnKeyword */);
23572             if (!canParseSemicolon()) {
23573                 node.expression = allowInAnd(parseExpression);
23574             }
23575             parseSemicolon();
23576             return finishNode(node);
23577         }
23578         function parseWithStatement() {
23579             var node = createNode(236 /* WithStatement */);
23580             parseExpected(112 /* WithKeyword */);
23581             parseExpected(20 /* OpenParenToken */);
23582             node.expression = allowInAnd(parseExpression);
23583             parseExpected(21 /* CloseParenToken */);
23584             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23585             return finishNode(node);
23586         }
23587         function parseCaseClause() {
23588             var node = createNode(277 /* CaseClause */);
23589             parseExpected(78 /* CaseKeyword */);
23590             node.expression = allowInAnd(parseExpression);
23591             parseExpected(58 /* ColonToken */);
23592             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23593             return finishNode(node);
23594         }
23595         function parseDefaultClause() {
23596             var node = createNode(278 /* DefaultClause */);
23597             parseExpected(84 /* DefaultKeyword */);
23598             parseExpected(58 /* ColonToken */);
23599             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23600             return finishNode(node);
23601         }
23602         function parseCaseOrDefaultClause() {
23603             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23604         }
23605         function parseSwitchStatement() {
23606             var node = createNode(237 /* SwitchStatement */);
23607             parseExpected(103 /* SwitchKeyword */);
23608             parseExpected(20 /* OpenParenToken */);
23609             node.expression = allowInAnd(parseExpression);
23610             parseExpected(21 /* CloseParenToken */);
23611             var caseBlock = createNode(251 /* CaseBlock */);
23612             parseExpected(18 /* OpenBraceToken */);
23613             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23614             parseExpected(19 /* CloseBraceToken */);
23615             node.caseBlock = finishNode(caseBlock);
23616             return finishNode(node);
23617         }
23618         function parseThrowStatement() {
23619             // ThrowStatement[Yield] :
23620             //      throw [no LineTerminator here]Expression[In, ?Yield];
23621             // Because of automatic semicolon insertion, we need to report error if this
23622             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23623             // directly as that might consume an expression on the following line.
23624             // We just return 'undefined' in that case.  The actual error will be reported in the
23625             // grammar walker.
23626             var node = createNode(239 /* ThrowStatement */);
23627             parseExpected(105 /* ThrowKeyword */);
23628             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23629             parseSemicolon();
23630             return finishNode(node);
23631         }
23632         // TODO: Review for error recovery
23633         function parseTryStatement() {
23634             var node = createNode(240 /* TryStatement */);
23635             parseExpected(107 /* TryKeyword */);
23636             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23637             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23638             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23639             // one out no matter what.
23640             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23641                 parseExpected(92 /* FinallyKeyword */);
23642                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23643             }
23644             return finishNode(node);
23645         }
23646         function parseCatchClause() {
23647             var result = createNode(280 /* CatchClause */);
23648             parseExpected(79 /* CatchKeyword */);
23649             if (parseOptional(20 /* OpenParenToken */)) {
23650                 result.variableDeclaration = parseVariableDeclaration();
23651                 parseExpected(21 /* CloseParenToken */);
23652             }
23653             else {
23654                 // Keep shape of node to avoid degrading performance.
23655                 result.variableDeclaration = undefined;
23656             }
23657             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23658             return finishNode(result);
23659         }
23660         function parseDebuggerStatement() {
23661             var node = createNode(241 /* DebuggerStatement */);
23662             parseExpected(83 /* DebuggerKeyword */);
23663             parseSemicolon();
23664             return finishNode(node);
23665         }
23666         function parseExpressionOrLabeledStatement() {
23667             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23668             // out an expression, seeing if it is identifier and then seeing if it is followed by
23669             // a colon.
23670             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23671             var expression = allowInAnd(parseExpression);
23672             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23673                 node.kind = 238 /* LabeledStatement */;
23674                 node.label = expression;
23675                 node.statement = parseStatement();
23676             }
23677             else {
23678                 node.kind = 226 /* ExpressionStatement */;
23679                 node.expression = expression;
23680                 parseSemicolon();
23681             }
23682             return finishNode(node);
23683         }
23684         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23685             nextToken();
23686             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23687         }
23688         function nextTokenIsClassKeywordOnSameLine() {
23689             nextToken();
23690             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23691         }
23692         function nextTokenIsFunctionKeywordOnSameLine() {
23693             nextToken();
23694             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23695         }
23696         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23697             nextToken();
23698             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23699         }
23700         function isDeclaration() {
23701             while (true) {
23702                 switch (token()) {
23703                     case 109 /* VarKeyword */:
23704                     case 115 /* LetKeyword */:
23705                     case 81 /* ConstKeyword */:
23706                     case 94 /* FunctionKeyword */:
23707                     case 80 /* ClassKeyword */:
23708                     case 88 /* EnumKeyword */:
23709                         return true;
23710                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23711                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23712                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23713                     //
23714                     //    namespace n
23715                     //
23716                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23717                     //
23718                     //    namespace
23719                     //    n
23720                     //
23721                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23722                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23723                     //
23724                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23725                     //
23726                     //   "use strict"
23727                     //   interface
23728                     //   I {}
23729                     //
23730                     // could be legal, it would add complexity for very little gain.
23731                     case 114 /* InterfaceKeyword */:
23732                     case 145 /* TypeKeyword */:
23733                         return nextTokenIsIdentifierOnSameLine();
23734                     case 135 /* ModuleKeyword */:
23735                     case 136 /* NamespaceKeyword */:
23736                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23737                     case 122 /* AbstractKeyword */:
23738                     case 126 /* AsyncKeyword */:
23739                     case 130 /* DeclareKeyword */:
23740                     case 117 /* PrivateKeyword */:
23741                     case 118 /* ProtectedKeyword */:
23742                     case 119 /* PublicKeyword */:
23743                     case 138 /* ReadonlyKeyword */:
23744                         nextToken();
23745                         // ASI takes effect for this modifier.
23746                         if (scanner.hasPrecedingLineBreak()) {
23747                             return false;
23748                         }
23749                         continue;
23750                     case 150 /* GlobalKeyword */:
23751                         nextToken();
23752                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23753                     case 96 /* ImportKeyword */:
23754                         nextToken();
23755                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23756                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23757                     case 89 /* ExportKeyword */:
23758                         var currentToken_1 = nextToken();
23759                         if (currentToken_1 === 145 /* TypeKeyword */) {
23760                             currentToken_1 = lookAhead(nextToken);
23761                         }
23762                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23763                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23764                             currentToken_1 === 123 /* AsKeyword */) {
23765                             return true;
23766                         }
23767                         continue;
23768                     case 120 /* StaticKeyword */:
23769                         nextToken();
23770                         continue;
23771                     default:
23772                         return false;
23773                 }
23774             }
23775         }
23776         function isStartOfDeclaration() {
23777             return lookAhead(isDeclaration);
23778         }
23779         function isStartOfStatement() {
23780             switch (token()) {
23781                 case 59 /* AtToken */:
23782                 case 26 /* SemicolonToken */:
23783                 case 18 /* OpenBraceToken */:
23784                 case 109 /* VarKeyword */:
23785                 case 115 /* LetKeyword */:
23786                 case 94 /* FunctionKeyword */:
23787                 case 80 /* ClassKeyword */:
23788                 case 88 /* EnumKeyword */:
23789                 case 95 /* IfKeyword */:
23790                 case 86 /* DoKeyword */:
23791                 case 111 /* WhileKeyword */:
23792                 case 93 /* ForKeyword */:
23793                 case 82 /* ContinueKeyword */:
23794                 case 77 /* BreakKeyword */:
23795                 case 101 /* ReturnKeyword */:
23796                 case 112 /* WithKeyword */:
23797                 case 103 /* SwitchKeyword */:
23798                 case 105 /* ThrowKeyword */:
23799                 case 107 /* TryKeyword */:
23800                 case 83 /* DebuggerKeyword */:
23801                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23802                 // however, we say they are here so that we may gracefully parse them and error later.
23803                 // falls through
23804                 case 79 /* CatchKeyword */:
23805                 case 92 /* FinallyKeyword */:
23806                     return true;
23807                 case 96 /* ImportKeyword */:
23808                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23809                 case 81 /* ConstKeyword */:
23810                 case 89 /* ExportKeyword */:
23811                     return isStartOfDeclaration();
23812                 case 126 /* AsyncKeyword */:
23813                 case 130 /* DeclareKeyword */:
23814                 case 114 /* InterfaceKeyword */:
23815                 case 135 /* ModuleKeyword */:
23816                 case 136 /* NamespaceKeyword */:
23817                 case 145 /* TypeKeyword */:
23818                 case 150 /* GlobalKeyword */:
23819                     // When these don't start a declaration, they're an identifier in an expression statement
23820                     return true;
23821                 case 119 /* PublicKeyword */:
23822                 case 117 /* PrivateKeyword */:
23823                 case 118 /* ProtectedKeyword */:
23824                 case 120 /* StaticKeyword */:
23825                 case 138 /* ReadonlyKeyword */:
23826                     // When these don't start a declaration, they may be the start of a class member if an identifier
23827                     // immediately follows. Otherwise they're an identifier in an expression statement.
23828                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23829                 default:
23830                     return isStartOfExpression();
23831             }
23832         }
23833         function nextTokenIsIdentifierOrStartOfDestructuring() {
23834             nextToken();
23835             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23836         }
23837         function isLetDeclaration() {
23838             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
23839             // or [.
23840             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
23841         }
23842         function parseStatement() {
23843             switch (token()) {
23844                 case 26 /* SemicolonToken */:
23845                     return parseEmptyStatement();
23846                 case 18 /* OpenBraceToken */:
23847                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
23848                 case 109 /* VarKeyword */:
23849                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23850                 case 115 /* LetKeyword */:
23851                     if (isLetDeclaration()) {
23852                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23853                     }
23854                     break;
23855                 case 94 /* FunctionKeyword */:
23856                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
23857                 case 80 /* ClassKeyword */:
23858                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
23859                 case 95 /* IfKeyword */:
23860                     return parseIfStatement();
23861                 case 86 /* DoKeyword */:
23862                     return parseDoStatement();
23863                 case 111 /* WhileKeyword */:
23864                     return parseWhileStatement();
23865                 case 93 /* ForKeyword */:
23866                     return parseForOrForInOrForOfStatement();
23867                 case 82 /* ContinueKeyword */:
23868                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
23869                 case 77 /* BreakKeyword */:
23870                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
23871                 case 101 /* ReturnKeyword */:
23872                     return parseReturnStatement();
23873                 case 112 /* WithKeyword */:
23874                     return parseWithStatement();
23875                 case 103 /* SwitchKeyword */:
23876                     return parseSwitchStatement();
23877                 case 105 /* ThrowKeyword */:
23878                     return parseThrowStatement();
23879                 case 107 /* TryKeyword */:
23880                 // Include 'catch' and 'finally' for error recovery.
23881                 // falls through
23882                 case 79 /* CatchKeyword */:
23883                 case 92 /* FinallyKeyword */:
23884                     return parseTryStatement();
23885                 case 83 /* DebuggerKeyword */:
23886                     return parseDebuggerStatement();
23887                 case 59 /* AtToken */:
23888                     return parseDeclaration();
23889                 case 126 /* AsyncKeyword */:
23890                 case 114 /* InterfaceKeyword */:
23891                 case 145 /* TypeKeyword */:
23892                 case 135 /* ModuleKeyword */:
23893                 case 136 /* NamespaceKeyword */:
23894                 case 130 /* DeclareKeyword */:
23895                 case 81 /* ConstKeyword */:
23896                 case 88 /* EnumKeyword */:
23897                 case 89 /* ExportKeyword */:
23898                 case 96 /* ImportKeyword */:
23899                 case 117 /* PrivateKeyword */:
23900                 case 118 /* ProtectedKeyword */:
23901                 case 119 /* PublicKeyword */:
23902                 case 122 /* AbstractKeyword */:
23903                 case 120 /* StaticKeyword */:
23904                 case 138 /* ReadonlyKeyword */:
23905                 case 150 /* GlobalKeyword */:
23906                     if (isStartOfDeclaration()) {
23907                         return parseDeclaration();
23908                     }
23909                     break;
23910             }
23911             return parseExpressionOrLabeledStatement();
23912         }
23913         function isDeclareModifier(modifier) {
23914             return modifier.kind === 130 /* DeclareKeyword */;
23915         }
23916         function parseDeclaration() {
23917             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
23918             // `parseListElement` attempted to get the reused node at this position,
23919             // but the ambient context flag was not yet set, so the node appeared
23920             // not reusable in that context.
23921             var isAmbient = ts.some(modifiers, isDeclareModifier);
23922             if (isAmbient) {
23923                 var node_3 = tryReuseAmbientDeclaration();
23924                 if (node_3) {
23925                     return node_3;
23926                 }
23927             }
23928             var node = createNodeWithJSDoc(0 /* Unknown */);
23929             node.decorators = parseDecorators();
23930             node.modifiers = parseModifiers();
23931             if (isAmbient) {
23932                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
23933                     var m = _a[_i];
23934                     m.flags |= 8388608 /* Ambient */;
23935                 }
23936                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
23937             }
23938             else {
23939                 return parseDeclarationWorker(node);
23940             }
23941         }
23942         function tryReuseAmbientDeclaration() {
23943             return doInsideOfContext(8388608 /* Ambient */, function () {
23944                 var node = currentNode(parsingContext);
23945                 if (node) {
23946                     return consumeNode(node);
23947                 }
23948             });
23949         }
23950         function parseDeclarationWorker(node) {
23951             switch (token()) {
23952                 case 109 /* VarKeyword */:
23953                 case 115 /* LetKeyword */:
23954                 case 81 /* ConstKeyword */:
23955                     return parseVariableStatement(node);
23956                 case 94 /* FunctionKeyword */:
23957                     return parseFunctionDeclaration(node);
23958                 case 80 /* ClassKeyword */:
23959                     return parseClassDeclaration(node);
23960                 case 114 /* InterfaceKeyword */:
23961                     return parseInterfaceDeclaration(node);
23962                 case 145 /* TypeKeyword */:
23963                     return parseTypeAliasDeclaration(node);
23964                 case 88 /* EnumKeyword */:
23965                     return parseEnumDeclaration(node);
23966                 case 150 /* GlobalKeyword */:
23967                 case 135 /* ModuleKeyword */:
23968                 case 136 /* NamespaceKeyword */:
23969                     return parseModuleDeclaration(node);
23970                 case 96 /* ImportKeyword */:
23971                     return parseImportDeclarationOrImportEqualsDeclaration(node);
23972                 case 89 /* ExportKeyword */:
23973                     nextToken();
23974                     switch (token()) {
23975                         case 84 /* DefaultKeyword */:
23976                         case 62 /* EqualsToken */:
23977                             return parseExportAssignment(node);
23978                         case 123 /* AsKeyword */:
23979                             return parseNamespaceExportDeclaration(node);
23980                         default:
23981                             return parseExportDeclaration(node);
23982                     }
23983                 default:
23984                     if (node.decorators || node.modifiers) {
23985                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
23986                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
23987                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
23988                         missing.pos = node.pos;
23989                         missing.decorators = node.decorators;
23990                         missing.modifiers = node.modifiers;
23991                         return finishNode(missing);
23992                     }
23993                     return undefined; // TODO: GH#18217
23994             }
23995         }
23996         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
23997             nextToken();
23998             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
23999         }
24000         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24001             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24002                 parseSemicolon();
24003                 return;
24004             }
24005             return parseFunctionBlock(flags, diagnosticMessage);
24006         }
24007         // DECLARATIONS
24008         function parseArrayBindingElement() {
24009             if (token() === 27 /* CommaToken */) {
24010                 return createNode(215 /* OmittedExpression */);
24011             }
24012             var node = createNode(191 /* BindingElement */);
24013             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24014             node.name = parseIdentifierOrPattern();
24015             node.initializer = parseInitializer();
24016             return finishNode(node);
24017         }
24018         function parseObjectBindingElement() {
24019             var node = createNode(191 /* BindingElement */);
24020             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24021             var tokenIsIdentifier = isIdentifier();
24022             var propertyName = parsePropertyName();
24023             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24024                 node.name = propertyName;
24025             }
24026             else {
24027                 parseExpected(58 /* ColonToken */);
24028                 node.propertyName = propertyName;
24029                 node.name = parseIdentifierOrPattern();
24030             }
24031             node.initializer = parseInitializer();
24032             return finishNode(node);
24033         }
24034         function parseObjectBindingPattern() {
24035             var node = createNode(189 /* ObjectBindingPattern */);
24036             parseExpected(18 /* OpenBraceToken */);
24037             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24038             parseExpected(19 /* CloseBraceToken */);
24039             return finishNode(node);
24040         }
24041         function parseArrayBindingPattern() {
24042             var node = createNode(190 /* ArrayBindingPattern */);
24043             parseExpected(22 /* OpenBracketToken */);
24044             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24045             parseExpected(23 /* CloseBracketToken */);
24046             return finishNode(node);
24047         }
24048         function isIdentifierOrPrivateIdentifierOrPattern() {
24049             return token() === 18 /* OpenBraceToken */
24050                 || token() === 22 /* OpenBracketToken */
24051                 || token() === 76 /* PrivateIdentifier */
24052                 || isIdentifier();
24053         }
24054         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24055             if (token() === 22 /* OpenBracketToken */) {
24056                 return parseArrayBindingPattern();
24057             }
24058             if (token() === 18 /* OpenBraceToken */) {
24059                 return parseObjectBindingPattern();
24060             }
24061             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24062         }
24063         function parseVariableDeclarationAllowExclamation() {
24064             return parseVariableDeclaration(/*allowExclamation*/ true);
24065         }
24066         function parseVariableDeclaration(allowExclamation) {
24067             var node = createNode(242 /* VariableDeclaration */);
24068             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24069             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24070                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24071                 node.exclamationToken = parseTokenNode();
24072             }
24073             node.type = parseTypeAnnotation();
24074             if (!isInOrOfKeyword(token())) {
24075                 node.initializer = parseInitializer();
24076             }
24077             return finishNode(node);
24078         }
24079         function parseVariableDeclarationList(inForStatementInitializer) {
24080             var node = createNode(243 /* VariableDeclarationList */);
24081             switch (token()) {
24082                 case 109 /* VarKeyword */:
24083                     break;
24084                 case 115 /* LetKeyword */:
24085                     node.flags |= 1 /* Let */;
24086                     break;
24087                 case 81 /* ConstKeyword */:
24088                     node.flags |= 2 /* Const */;
24089                     break;
24090                 default:
24091                     ts.Debug.fail();
24092             }
24093             nextToken();
24094             // The user may have written the following:
24095             //
24096             //    for (let of X) { }
24097             //
24098             // In this case, we want to parse an empty declaration list, and then parse 'of'
24099             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24100             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24101             // this context.
24102             // The checker will then give an error that there is an empty declaration list.
24103             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24104                 node.declarations = createMissingList();
24105             }
24106             else {
24107                 var savedDisallowIn = inDisallowInContext();
24108                 setDisallowInContext(inForStatementInitializer);
24109                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24110                 setDisallowInContext(savedDisallowIn);
24111             }
24112             return finishNode(node);
24113         }
24114         function canFollowContextualOfKeyword() {
24115             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24116         }
24117         function parseVariableStatement(node) {
24118             node.kind = 225 /* VariableStatement */;
24119             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24120             parseSemicolon();
24121             return finishNode(node);
24122         }
24123         function parseFunctionDeclaration(node) {
24124             node.kind = 244 /* FunctionDeclaration */;
24125             parseExpected(94 /* FunctionKeyword */);
24126             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24127             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24128             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24129             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24130             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24131             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24132             return finishNode(node);
24133         }
24134         function parseConstructorName() {
24135             if (token() === 129 /* ConstructorKeyword */) {
24136                 return parseExpected(129 /* ConstructorKeyword */);
24137             }
24138             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24139                 return tryParse(function () {
24140                     var literalNode = parseLiteralNode();
24141                     return literalNode.text === "constructor" ? literalNode : undefined;
24142                 });
24143             }
24144         }
24145         function tryParseConstructorDeclaration(node) {
24146             return tryParse(function () {
24147                 if (parseConstructorName()) {
24148                     node.kind = 162 /* Constructor */;
24149                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24150                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24151                     return finishNode(node);
24152                 }
24153             });
24154         }
24155         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24156             node.kind = 161 /* MethodDeclaration */;
24157             node.asteriskToken = asteriskToken;
24158             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24159             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24160             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24161             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24162             return finishNode(node);
24163         }
24164         function parsePropertyDeclaration(node) {
24165             node.kind = 159 /* PropertyDeclaration */;
24166             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24167                 node.exclamationToken = parseTokenNode();
24168             }
24169             node.type = parseTypeAnnotation();
24170             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24171             parseSemicolon();
24172             return finishNode(node);
24173         }
24174         function parsePropertyOrMethodDeclaration(node) {
24175             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24176             node.name = parsePropertyName();
24177             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24178             // report an error in the grammar checker.
24179             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24180             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24181                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24182             }
24183             return parsePropertyDeclaration(node);
24184         }
24185         function parseAccessorDeclaration(node, kind) {
24186             node.kind = kind;
24187             node.name = parsePropertyName();
24188             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24189             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24190             return finishNode(node);
24191         }
24192         function isClassMemberStart() {
24193             var idToken;
24194             if (token() === 59 /* AtToken */) {
24195                 return true;
24196             }
24197             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24198             while (ts.isModifierKind(token())) {
24199                 idToken = token();
24200                 // If the idToken is a class modifier (protected, private, public, and static), it is
24201                 // certain that we are starting to parse class member. This allows better error recovery
24202                 // Example:
24203                 //      public foo() ...     // true
24204                 //      public @dec blah ... // true; we will then report an error later
24205                 //      export public ...    // true; we will then report an error later
24206                 if (ts.isClassMemberModifier(idToken)) {
24207                     return true;
24208                 }
24209                 nextToken();
24210             }
24211             if (token() === 41 /* AsteriskToken */) {
24212                 return true;
24213             }
24214             // Try to get the first property-like token following all modifiers.
24215             // This can either be an identifier or the 'get' or 'set' keywords.
24216             if (isLiteralPropertyName()) {
24217                 idToken = token();
24218                 nextToken();
24219             }
24220             // Index signatures and computed properties are class members; we can parse.
24221             if (token() === 22 /* OpenBracketToken */) {
24222                 return true;
24223             }
24224             // If we were able to get any potential identifier...
24225             if (idToken !== undefined) {
24226                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24227                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24228                     return true;
24229                 }
24230                 // If it *is* a keyword, but not an accessor, check a little farther along
24231                 // to see if it should actually be parsed as a class member.
24232                 switch (token()) {
24233                     case 20 /* OpenParenToken */: // Method declaration
24234                     case 29 /* LessThanToken */: // Generic Method declaration
24235                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24236                     case 58 /* ColonToken */: // Type Annotation for declaration
24237                     case 62 /* EqualsToken */: // Initializer for declaration
24238                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24239                         return true;
24240                     default:
24241                         // Covers
24242                         //  - Semicolons     (declaration termination)
24243                         //  - Closing braces (end-of-class, must be declaration)
24244                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24245                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24246                         return canParseSemicolon();
24247                 }
24248             }
24249             return false;
24250         }
24251         function parseDecorators() {
24252             var list;
24253             var listPos = getNodePos();
24254             while (true) {
24255                 var decoratorStart = getNodePos();
24256                 if (!parseOptional(59 /* AtToken */)) {
24257                     break;
24258                 }
24259                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24260                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24261                 finishNode(decorator);
24262                 (list || (list = [])).push(decorator);
24263             }
24264             return list && createNodeArray(list, listPos);
24265         }
24266         /*
24267          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24268          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24269          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24270          *
24271          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24272          */
24273         function parseModifiers(permitInvalidConstAsModifier) {
24274             var list;
24275             var listPos = getNodePos();
24276             while (true) {
24277                 var modifierStart = scanner.getStartPos();
24278                 var modifierKind = token();
24279                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24280                     // We need to ensure that any subsequent modifiers appear on the same line
24281                     // so that when 'const' is a standalone declaration, we don't issue an error.
24282                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24283                         break;
24284                     }
24285                 }
24286                 else {
24287                     if (!parseAnyContextualModifier()) {
24288                         break;
24289                     }
24290                 }
24291                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24292                 (list || (list = [])).push(modifier);
24293             }
24294             return list && createNodeArray(list, listPos);
24295         }
24296         function parseModifiersForArrowFunction() {
24297             var modifiers;
24298             if (token() === 126 /* AsyncKeyword */) {
24299                 var modifierStart = scanner.getStartPos();
24300                 var modifierKind = token();
24301                 nextToken();
24302                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24303                 modifiers = createNodeArray([modifier], modifierStart);
24304             }
24305             return modifiers;
24306         }
24307         function parseClassElement() {
24308             if (token() === 26 /* SemicolonToken */) {
24309                 var result = createNode(222 /* SemicolonClassElement */);
24310                 nextToken();
24311                 return finishNode(result);
24312             }
24313             var node = createNodeWithJSDoc(0 /* Unknown */);
24314             node.decorators = parseDecorators();
24315             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24316             if (parseContextualModifier(131 /* GetKeyword */)) {
24317                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24318             }
24319             if (parseContextualModifier(142 /* SetKeyword */)) {
24320                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24321             }
24322             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24323                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24324                 if (constructorDeclaration) {
24325                     return constructorDeclaration;
24326                 }
24327             }
24328             if (isIndexSignature()) {
24329                 return parseIndexSignatureDeclaration(node);
24330             }
24331             // It is very important that we check this *after* checking indexers because
24332             // the [ token can start an index signature or a computed property name
24333             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24334                 token() === 10 /* StringLiteral */ ||
24335                 token() === 8 /* NumericLiteral */ ||
24336                 token() === 41 /* AsteriskToken */ ||
24337                 token() === 22 /* OpenBracketToken */) {
24338                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24339                 if (isAmbient) {
24340                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24341                         var m = _a[_i];
24342                         m.flags |= 8388608 /* Ambient */;
24343                     }
24344                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24345                 }
24346                 else {
24347                     return parsePropertyOrMethodDeclaration(node);
24348                 }
24349             }
24350             if (node.decorators || node.modifiers) {
24351                 // treat this as a property declaration with a missing name.
24352                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24353                 return parsePropertyDeclaration(node);
24354             }
24355             // 'isClassMemberStart' should have hinted not to attempt parsing.
24356             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24357         }
24358         function parseClassExpression() {
24359             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24360         }
24361         function parseClassDeclaration(node) {
24362             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24363         }
24364         function parseClassDeclarationOrExpression(node, kind) {
24365             node.kind = kind;
24366             parseExpected(80 /* ClassKeyword */);
24367             node.name = parseNameOfClassDeclarationOrExpression();
24368             node.typeParameters = parseTypeParameters();
24369             node.heritageClauses = parseHeritageClauses();
24370             if (parseExpected(18 /* OpenBraceToken */)) {
24371                 // ClassTail[Yield,Await] : (Modified) See 14.5
24372                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24373                 node.members = parseClassMembers();
24374                 parseExpected(19 /* CloseBraceToken */);
24375             }
24376             else {
24377                 node.members = createMissingList();
24378             }
24379             return finishNode(node);
24380         }
24381         function parseNameOfClassDeclarationOrExpression() {
24382             // implements is a future reserved word so
24383             // 'class implements' might mean either
24384             // - class expression with omitted name, 'implements' starts heritage clause
24385             // - class with name 'implements'
24386             // 'isImplementsClause' helps to disambiguate between these two cases
24387             return isIdentifier() && !isImplementsClause()
24388                 ? parseIdentifier()
24389                 : undefined;
24390         }
24391         function isImplementsClause() {
24392             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24393         }
24394         function parseHeritageClauses() {
24395             // ClassTail[Yield,Await] : (Modified) See 14.5
24396             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24397             if (isHeritageClause()) {
24398                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24399             }
24400             return undefined;
24401         }
24402         function parseHeritageClause() {
24403             var tok = token();
24404             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24405             var node = createNode(279 /* HeritageClause */);
24406             node.token = tok;
24407             nextToken();
24408             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24409             return finishNode(node);
24410         }
24411         function parseExpressionWithTypeArguments() {
24412             var node = createNode(216 /* ExpressionWithTypeArguments */);
24413             node.expression = parseLeftHandSideExpressionOrHigher();
24414             node.typeArguments = tryParseTypeArguments();
24415             return finishNode(node);
24416         }
24417         function tryParseTypeArguments() {
24418             return token() === 29 /* LessThanToken */ ?
24419                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24420         }
24421         function isHeritageClause() {
24422             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24423         }
24424         function parseClassMembers() {
24425             return parseList(5 /* ClassMembers */, parseClassElement);
24426         }
24427         function parseInterfaceDeclaration(node) {
24428             node.kind = 246 /* InterfaceDeclaration */;
24429             parseExpected(114 /* InterfaceKeyword */);
24430             node.name = parseIdentifier();
24431             node.typeParameters = parseTypeParameters();
24432             node.heritageClauses = parseHeritageClauses();
24433             node.members = parseObjectTypeMembers();
24434             return finishNode(node);
24435         }
24436         function parseTypeAliasDeclaration(node) {
24437             node.kind = 247 /* TypeAliasDeclaration */;
24438             parseExpected(145 /* TypeKeyword */);
24439             node.name = parseIdentifier();
24440             node.typeParameters = parseTypeParameters();
24441             parseExpected(62 /* EqualsToken */);
24442             node.type = parseType();
24443             parseSemicolon();
24444             return finishNode(node);
24445         }
24446         // In an ambient declaration, the grammar only allows integer literals as initializers.
24447         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24448         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24449         // or any time an integer literal initializer is encountered.
24450         function parseEnumMember() {
24451             var node = createNodeWithJSDoc(284 /* EnumMember */);
24452             node.name = parsePropertyName();
24453             node.initializer = allowInAnd(parseInitializer);
24454             return finishNode(node);
24455         }
24456         function parseEnumDeclaration(node) {
24457             node.kind = 248 /* EnumDeclaration */;
24458             parseExpected(88 /* EnumKeyword */);
24459             node.name = parseIdentifier();
24460             if (parseExpected(18 /* OpenBraceToken */)) {
24461                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24462                 parseExpected(19 /* CloseBraceToken */);
24463             }
24464             else {
24465                 node.members = createMissingList();
24466             }
24467             return finishNode(node);
24468         }
24469         function parseModuleBlock() {
24470             var node = createNode(250 /* ModuleBlock */);
24471             if (parseExpected(18 /* OpenBraceToken */)) {
24472                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24473                 parseExpected(19 /* CloseBraceToken */);
24474             }
24475             else {
24476                 node.statements = createMissingList();
24477             }
24478             return finishNode(node);
24479         }
24480         function parseModuleOrNamespaceDeclaration(node, flags) {
24481             node.kind = 249 /* ModuleDeclaration */;
24482             // If we are parsing a dotted namespace name, we want to
24483             // propagate the 'Namespace' flag across the names if set.
24484             var namespaceFlag = flags & 16 /* Namespace */;
24485             node.flags |= flags;
24486             node.name = parseIdentifier();
24487             node.body = parseOptional(24 /* DotToken */)
24488                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24489                 : parseModuleBlock();
24490             return finishNode(node);
24491         }
24492         function parseAmbientExternalModuleDeclaration(node) {
24493             node.kind = 249 /* ModuleDeclaration */;
24494             if (token() === 150 /* GlobalKeyword */) {
24495                 // parse 'global' as name of global scope augmentation
24496                 node.name = parseIdentifier();
24497                 node.flags |= 1024 /* GlobalAugmentation */;
24498             }
24499             else {
24500                 node.name = parseLiteralNode();
24501                 node.name.text = internIdentifier(node.name.text);
24502             }
24503             if (token() === 18 /* OpenBraceToken */) {
24504                 node.body = parseModuleBlock();
24505             }
24506             else {
24507                 parseSemicolon();
24508             }
24509             return finishNode(node);
24510         }
24511         function parseModuleDeclaration(node) {
24512             var flags = 0;
24513             if (token() === 150 /* GlobalKeyword */) {
24514                 // global augmentation
24515                 return parseAmbientExternalModuleDeclaration(node);
24516             }
24517             else if (parseOptional(136 /* NamespaceKeyword */)) {
24518                 flags |= 16 /* Namespace */;
24519             }
24520             else {
24521                 parseExpected(135 /* ModuleKeyword */);
24522                 if (token() === 10 /* StringLiteral */) {
24523                     return parseAmbientExternalModuleDeclaration(node);
24524                 }
24525             }
24526             return parseModuleOrNamespaceDeclaration(node, flags);
24527         }
24528         function isExternalModuleReference() {
24529             return token() === 139 /* RequireKeyword */ &&
24530                 lookAhead(nextTokenIsOpenParen);
24531         }
24532         function nextTokenIsOpenParen() {
24533             return nextToken() === 20 /* OpenParenToken */;
24534         }
24535         function nextTokenIsSlash() {
24536             return nextToken() === 43 /* SlashToken */;
24537         }
24538         function parseNamespaceExportDeclaration(node) {
24539             node.kind = 252 /* NamespaceExportDeclaration */;
24540             parseExpected(123 /* AsKeyword */);
24541             parseExpected(136 /* NamespaceKeyword */);
24542             node.name = parseIdentifier();
24543             parseSemicolon();
24544             return finishNode(node);
24545         }
24546         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24547             parseExpected(96 /* ImportKeyword */);
24548             var afterImportPos = scanner.getStartPos();
24549             var identifier;
24550             if (isIdentifier()) {
24551                 identifier = parseIdentifier();
24552             }
24553             var isTypeOnly = false;
24554             if (token() !== 149 /* FromKeyword */ &&
24555                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24556                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24557                 isTypeOnly = true;
24558                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24559             }
24560             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24561                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24562             }
24563             // Import statement
24564             node.kind = 254 /* ImportDeclaration */;
24565             // ImportDeclaration:
24566             //  import ImportClause from ModuleSpecifier ;
24567             //  import ModuleSpecifier;
24568             if (identifier || // import id
24569                 token() === 41 /* AsteriskToken */ || // import *
24570                 token() === 18 /* OpenBraceToken */ // import {
24571             ) {
24572                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24573                 parseExpected(149 /* FromKeyword */);
24574             }
24575             node.moduleSpecifier = parseModuleSpecifier();
24576             parseSemicolon();
24577             return finishNode(node);
24578         }
24579         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24580             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24581         }
24582         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24583             // In `import id ___`, the current token decides whether to produce
24584             // an ImportDeclaration or ImportEqualsDeclaration.
24585             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24586         }
24587         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24588             node.kind = 253 /* ImportEqualsDeclaration */;
24589             node.name = identifier;
24590             parseExpected(62 /* EqualsToken */);
24591             node.moduleReference = parseModuleReference();
24592             parseSemicolon();
24593             var finished = finishNode(node);
24594             if (isTypeOnly) {
24595                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24596             }
24597             return finished;
24598         }
24599         function parseImportClause(identifier, fullStart, isTypeOnly) {
24600             // ImportClause:
24601             //  ImportedDefaultBinding
24602             //  NameSpaceImport
24603             //  NamedImports
24604             //  ImportedDefaultBinding, NameSpaceImport
24605             //  ImportedDefaultBinding, NamedImports
24606             var importClause = createNode(255 /* ImportClause */, fullStart);
24607             importClause.isTypeOnly = isTypeOnly;
24608             if (identifier) {
24609                 // ImportedDefaultBinding:
24610                 //  ImportedBinding
24611                 importClause.name = identifier;
24612             }
24613             // If there was no default import or if there is comma token after default import
24614             // parse namespace or named imports
24615             if (!importClause.name ||
24616                 parseOptional(27 /* CommaToken */)) {
24617                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24618             }
24619             return finishNode(importClause);
24620         }
24621         function parseModuleReference() {
24622             return isExternalModuleReference()
24623                 ? parseExternalModuleReference()
24624                 : parseEntityName(/*allowReservedWords*/ false);
24625         }
24626         function parseExternalModuleReference() {
24627             var node = createNode(265 /* ExternalModuleReference */);
24628             parseExpected(139 /* RequireKeyword */);
24629             parseExpected(20 /* OpenParenToken */);
24630             node.expression = parseModuleSpecifier();
24631             parseExpected(21 /* CloseParenToken */);
24632             return finishNode(node);
24633         }
24634         function parseModuleSpecifier() {
24635             if (token() === 10 /* StringLiteral */) {
24636                 var result = parseLiteralNode();
24637                 result.text = internIdentifier(result.text);
24638                 return result;
24639             }
24640             else {
24641                 // We allow arbitrary expressions here, even though the grammar only allows string
24642                 // literals.  We check to ensure that it is only a string literal later in the grammar
24643                 // check pass.
24644                 return parseExpression();
24645             }
24646         }
24647         function parseNamespaceImport() {
24648             // NameSpaceImport:
24649             //  * as ImportedBinding
24650             var namespaceImport = createNode(256 /* NamespaceImport */);
24651             parseExpected(41 /* AsteriskToken */);
24652             parseExpected(123 /* AsKeyword */);
24653             namespaceImport.name = parseIdentifier();
24654             return finishNode(namespaceImport);
24655         }
24656         function parseNamedImportsOrExports(kind) {
24657             var node = createNode(kind);
24658             // NamedImports:
24659             //  { }
24660             //  { ImportsList }
24661             //  { ImportsList, }
24662             // ImportsList:
24663             //  ImportSpecifier
24664             //  ImportsList, ImportSpecifier
24665             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24666             return finishNode(node);
24667         }
24668         function parseExportSpecifier() {
24669             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24670         }
24671         function parseImportSpecifier() {
24672             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24673         }
24674         function parseImportOrExportSpecifier(kind) {
24675             var node = createNode(kind);
24676             // ImportSpecifier:
24677             //   BindingIdentifier
24678             //   IdentifierName as BindingIdentifier
24679             // ExportSpecifier:
24680             //   IdentifierName
24681             //   IdentifierName as IdentifierName
24682             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24683             var checkIdentifierStart = scanner.getTokenPos();
24684             var checkIdentifierEnd = scanner.getTextPos();
24685             var identifierName = parseIdentifierName();
24686             if (token() === 123 /* AsKeyword */) {
24687                 node.propertyName = identifierName;
24688                 parseExpected(123 /* AsKeyword */);
24689                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24690                 checkIdentifierStart = scanner.getTokenPos();
24691                 checkIdentifierEnd = scanner.getTextPos();
24692                 node.name = parseIdentifierName();
24693             }
24694             else {
24695                 node.name = identifierName;
24696             }
24697             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24698                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24699             }
24700             return finishNode(node);
24701         }
24702         function parseNamespaceExport(pos) {
24703             var node = createNode(262 /* NamespaceExport */, pos);
24704             node.name = parseIdentifier();
24705             return finishNode(node);
24706         }
24707         function parseExportDeclaration(node) {
24708             node.kind = 260 /* ExportDeclaration */;
24709             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24710             var namespaceExportPos = scanner.getStartPos();
24711             if (parseOptional(41 /* AsteriskToken */)) {
24712                 if (parseOptional(123 /* AsKeyword */)) {
24713                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24714                 }
24715                 parseExpected(149 /* FromKeyword */);
24716                 node.moduleSpecifier = parseModuleSpecifier();
24717             }
24718             else {
24719                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24720                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24721                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24722                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24723                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24724                     parseExpected(149 /* FromKeyword */);
24725                     node.moduleSpecifier = parseModuleSpecifier();
24726                 }
24727             }
24728             parseSemicolon();
24729             return finishNode(node);
24730         }
24731         function parseExportAssignment(node) {
24732             node.kind = 259 /* ExportAssignment */;
24733             if (parseOptional(62 /* EqualsToken */)) {
24734                 node.isExportEquals = true;
24735             }
24736             else {
24737                 parseExpected(84 /* DefaultKeyword */);
24738             }
24739             node.expression = parseAssignmentExpressionOrHigher();
24740             parseSemicolon();
24741             return finishNode(node);
24742         }
24743         function setExternalModuleIndicator(sourceFile) {
24744             // Try to use the first top-level import/export when available, then
24745             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24746             sourceFile.externalModuleIndicator =
24747                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24748                     getImportMetaIfNecessary(sourceFile);
24749         }
24750         function isAnExternalModuleIndicatorNode(node) {
24751             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24752                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24753                 || node.kind === 254 /* ImportDeclaration */
24754                 || node.kind === 259 /* ExportAssignment */
24755                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24756         }
24757         function getImportMetaIfNecessary(sourceFile) {
24758             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24759                 walkTreeForExternalModuleIndicators(sourceFile) :
24760                 undefined;
24761         }
24762         function walkTreeForExternalModuleIndicators(node) {
24763             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24764         }
24765         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24766         function hasModifierOfKind(node, kind) {
24767             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24768         }
24769         function isImportMeta(node) {
24770             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24771         }
24772         var ParsingContext;
24773         (function (ParsingContext) {
24774             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24775             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24776             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24777             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24778             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24779             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24780             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24781             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24782             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24783             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24784             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24785             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24786             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24787             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24788             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24789             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24790             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24791             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24792             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24793             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24794             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24795             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24796             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24797             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24798             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24799         })(ParsingContext || (ParsingContext = {}));
24800         var Tristate;
24801         (function (Tristate) {
24802             Tristate[Tristate["False"] = 0] = "False";
24803             Tristate[Tristate["True"] = 1] = "True";
24804             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24805         })(Tristate || (Tristate = {}));
24806         var JSDocParser;
24807         (function (JSDocParser) {
24808             function parseJSDocTypeExpressionForTests(content, start, length) {
24809                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24810                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24811                 scanner.setText(content, start, length);
24812                 currentToken = scanner.scan();
24813                 var jsDocTypeExpression = parseJSDocTypeExpression();
24814                 var diagnostics = parseDiagnostics;
24815                 clearState();
24816                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24817             }
24818             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24819             // Parses out a JSDoc type expression.
24820             function parseJSDocTypeExpression(mayOmitBraces) {
24821                 var result = createNode(294 /* JSDocTypeExpression */);
24822                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24823                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24824                 if (!mayOmitBraces || hasBrace) {
24825                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24826                 }
24827                 fixupParentReferences(result);
24828                 return finishNode(result);
24829             }
24830             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24831             function parseIsolatedJSDocComment(content, start, length) {
24832                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24833                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24834                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24835                 var diagnostics = parseDiagnostics;
24836                 clearState();
24837                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
24838             }
24839             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
24840             function parseJSDocComment(parent, start, length) {
24841                 var _a;
24842                 var saveToken = currentToken;
24843                 var saveParseDiagnosticsLength = parseDiagnostics.length;
24844                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
24845                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24846                 if (comment) {
24847                     comment.parent = parent;
24848                 }
24849                 if (contextFlags & 131072 /* JavaScriptFile */) {
24850                     if (!sourceFile.jsDocDiagnostics) {
24851                         sourceFile.jsDocDiagnostics = [];
24852                     }
24853                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
24854                 }
24855                 currentToken = saveToken;
24856                 parseDiagnostics.length = saveParseDiagnosticsLength;
24857                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
24858                 return comment;
24859             }
24860             JSDocParser.parseJSDocComment = parseJSDocComment;
24861             var JSDocState;
24862             (function (JSDocState) {
24863                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
24864                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
24865                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
24866                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
24867             })(JSDocState || (JSDocState = {}));
24868             var PropertyLikeParse;
24869             (function (PropertyLikeParse) {
24870                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
24871                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
24872                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
24873             })(PropertyLikeParse || (PropertyLikeParse = {}));
24874             function parseJSDocCommentWorker(start, length) {
24875                 if (start === void 0) { start = 0; }
24876                 var content = sourceText;
24877                 var end = length === undefined ? content.length : start + length;
24878                 length = end - start;
24879                 ts.Debug.assert(start >= 0);
24880                 ts.Debug.assert(start <= end);
24881                 ts.Debug.assert(end <= content.length);
24882                 // Check for /** (JSDoc opening part)
24883                 if (!isJSDocLikeText(content, start)) {
24884                     return undefined;
24885                 }
24886                 var tags;
24887                 var tagsPos;
24888                 var tagsEnd;
24889                 var comments = [];
24890                 // + 3 for leading /**, - 5 in total for /** */
24891                 return scanner.scanRange(start + 3, length - 5, function () {
24892                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
24893                     // This is so that /** * @type */ doesn't parse.
24894                     var state = 1 /* SawAsterisk */;
24895                     var margin;
24896                     // + 4 for leading '/** '
24897                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
24898                     function pushComment(text) {
24899                         if (!margin) {
24900                             margin = indent;
24901                         }
24902                         comments.push(text);
24903                         indent += text.length;
24904                     }
24905                     nextTokenJSDoc();
24906                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
24907                         ;
24908                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
24909                         state = 0 /* BeginningOfLine */;
24910                         indent = 0;
24911                     }
24912                     loop: while (true) {
24913                         switch (token()) {
24914                             case 59 /* AtToken */:
24915                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
24916                                     removeTrailingWhitespace(comments);
24917                                     addTag(parseTag(indent));
24918                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
24919                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
24920                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
24921                                     state = 0 /* BeginningOfLine */;
24922                                     margin = undefined;
24923                                 }
24924                                 else {
24925                                     pushComment(scanner.getTokenText());
24926                                 }
24927                                 break;
24928                             case 4 /* NewLineTrivia */:
24929                                 comments.push(scanner.getTokenText());
24930                                 state = 0 /* BeginningOfLine */;
24931                                 indent = 0;
24932                                 break;
24933                             case 41 /* AsteriskToken */:
24934                                 var asterisk = scanner.getTokenText();
24935                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
24936                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
24937                                     state = 2 /* SavingComments */;
24938                                     pushComment(asterisk);
24939                                 }
24940                                 else {
24941                                     // Ignore the first asterisk on a line
24942                                     state = 1 /* SawAsterisk */;
24943                                     indent += asterisk.length;
24944                                 }
24945                                 break;
24946                             case 5 /* WhitespaceTrivia */:
24947                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
24948                                 var whitespace = scanner.getTokenText();
24949                                 if (state === 2 /* SavingComments */) {
24950                                     comments.push(whitespace);
24951                                 }
24952                                 else if (margin !== undefined && indent + whitespace.length > margin) {
24953                                     comments.push(whitespace.slice(margin - indent - 1));
24954                                 }
24955                                 indent += whitespace.length;
24956                                 break;
24957                             case 1 /* EndOfFileToken */:
24958                                 break loop;
24959                             default:
24960                                 // Anything else is doc comment text. We just save it. Because it
24961                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
24962                                 // line break.
24963                                 state = 2 /* SavingComments */;
24964                                 pushComment(scanner.getTokenText());
24965                                 break;
24966                         }
24967                         nextTokenJSDoc();
24968                     }
24969                     removeLeadingNewlines(comments);
24970                     removeTrailingWhitespace(comments);
24971                     return createJSDocComment();
24972                 });
24973                 function removeLeadingNewlines(comments) {
24974                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
24975                         comments.shift();
24976                     }
24977                 }
24978                 function removeTrailingWhitespace(comments) {
24979                     while (comments.length && comments[comments.length - 1].trim() === "") {
24980                         comments.pop();
24981                     }
24982                 }
24983                 function createJSDocComment() {
24984                     var result = createNode(303 /* JSDocComment */, start);
24985                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
24986                     result.comment = comments.length ? comments.join("") : undefined;
24987                     return finishNode(result, end);
24988                 }
24989                 function isNextNonwhitespaceTokenEndOfFile() {
24990                     // We must use infinite lookahead, as there could be any number of newlines :(
24991                     while (true) {
24992                         nextTokenJSDoc();
24993                         if (token() === 1 /* EndOfFileToken */) {
24994                             return true;
24995                         }
24996                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
24997                             return false;
24998                         }
24999                     }
25000                 }
25001                 function skipWhitespace() {
25002                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25003                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25004                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25005                         }
25006                     }
25007                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25008                         nextTokenJSDoc();
25009                     }
25010                 }
25011                 function skipWhitespaceOrAsterisk() {
25012                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25013                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25014                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25015                         }
25016                     }
25017                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25018                     var seenLineBreak = false;
25019                     var indentText = "";
25020                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25021                         indentText += scanner.getTokenText();
25022                         if (token() === 4 /* NewLineTrivia */) {
25023                             precedingLineBreak = true;
25024                             seenLineBreak = true;
25025                             indentText = "";
25026                         }
25027                         else if (token() === 41 /* AsteriskToken */) {
25028                             precedingLineBreak = false;
25029                         }
25030                         nextTokenJSDoc();
25031                     }
25032                     return seenLineBreak ? indentText : "";
25033                 }
25034                 function parseTag(margin) {
25035                     ts.Debug.assert(token() === 59 /* AtToken */);
25036                     var start = scanner.getTokenPos();
25037                     nextTokenJSDoc();
25038                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25039                     var indentText = skipWhitespaceOrAsterisk();
25040                     var tag;
25041                     switch (tagName.escapedText) {
25042                         case "author":
25043                             tag = parseAuthorTag(start, tagName, margin);
25044                             break;
25045                         case "implements":
25046                             tag = parseImplementsTag(start, tagName);
25047                             break;
25048                         case "augments":
25049                         case "extends":
25050                             tag = parseAugmentsTag(start, tagName);
25051                             break;
25052                         case "class":
25053                         case "constructor":
25054                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25055                             break;
25056                         case "public":
25057                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25058                             break;
25059                         case "private":
25060                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25061                             break;
25062                         case "protected":
25063                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25064                             break;
25065                         case "readonly":
25066                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25067                             break;
25068                         case "this":
25069                             tag = parseThisTag(start, tagName);
25070                             break;
25071                         case "enum":
25072                             tag = parseEnumTag(start, tagName);
25073                             break;
25074                         case "arg":
25075                         case "argument":
25076                         case "param":
25077                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25078                         case "return":
25079                         case "returns":
25080                             tag = parseReturnTag(start, tagName);
25081                             break;
25082                         case "template":
25083                             tag = parseTemplateTag(start, tagName);
25084                             break;
25085                         case "type":
25086                             tag = parseTypeTag(start, tagName);
25087                             break;
25088                         case "typedef":
25089                             tag = parseTypedefTag(start, tagName, margin);
25090                             break;
25091                         case "callback":
25092                             tag = parseCallbackTag(start, tagName, margin);
25093                             break;
25094                         default:
25095                             tag = parseUnknownTag(start, tagName);
25096                             break;
25097                     }
25098                     if (!tag.comment) {
25099                         // some tags, like typedef and callback, have already parsed their comments earlier
25100                         if (!indentText) {
25101                             margin += tag.end - tag.pos;
25102                         }
25103                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25104                     }
25105                     return tag;
25106                 }
25107                 function parseTagComments(indent, initialMargin) {
25108                     var comments = [];
25109                     var state = 0 /* BeginningOfLine */;
25110                     var margin;
25111                     function pushComment(text) {
25112                         if (!margin) {
25113                             margin = indent;
25114                         }
25115                         comments.push(text);
25116                         indent += text.length;
25117                     }
25118                     if (initialMargin !== undefined) {
25119                         // jump straight to saving comments if there is some initial indentation
25120                         if (initialMargin !== "") {
25121                             pushComment(initialMargin);
25122                         }
25123                         state = 1 /* SawAsterisk */;
25124                     }
25125                     var tok = token();
25126                     loop: while (true) {
25127                         switch (tok) {
25128                             case 4 /* NewLineTrivia */:
25129                                 if (state >= 1 /* SawAsterisk */) {
25130                                     state = 0 /* BeginningOfLine */;
25131                                     // don't use pushComment here because we want to keep the margin unchanged
25132                                     comments.push(scanner.getTokenText());
25133                                 }
25134                                 indent = 0;
25135                                 break;
25136                             case 59 /* AtToken */:
25137                                 if (state === 3 /* SavingBackticks */) {
25138                                     comments.push(scanner.getTokenText());
25139                                     break;
25140                                 }
25141                                 scanner.setTextPos(scanner.getTextPos() - 1);
25142                             // falls through
25143                             case 1 /* EndOfFileToken */:
25144                                 // Done
25145                                 break loop;
25146                             case 5 /* WhitespaceTrivia */:
25147                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25148                                     pushComment(scanner.getTokenText());
25149                                 }
25150                                 else {
25151                                     var whitespace = scanner.getTokenText();
25152                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25153                                     if (margin !== undefined && indent + whitespace.length > margin) {
25154                                         comments.push(whitespace.slice(margin - indent));
25155                                     }
25156                                     indent += whitespace.length;
25157                                 }
25158                                 break;
25159                             case 18 /* OpenBraceToken */:
25160                                 state = 2 /* SavingComments */;
25161                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25162                                     pushComment(scanner.getTokenText());
25163                                     nextTokenJSDoc();
25164                                     pushComment(scanner.getTokenText());
25165                                     nextTokenJSDoc();
25166                                 }
25167                                 pushComment(scanner.getTokenText());
25168                                 break;
25169                             case 61 /* BacktickToken */:
25170                                 if (state === 3 /* SavingBackticks */) {
25171                                     state = 2 /* SavingComments */;
25172                                 }
25173                                 else {
25174                                     state = 3 /* SavingBackticks */;
25175                                 }
25176                                 pushComment(scanner.getTokenText());
25177                                 break;
25178                             case 41 /* AsteriskToken */:
25179                                 if (state === 0 /* BeginningOfLine */) {
25180                                     // leading asterisks start recording on the *next* (non-whitespace) token
25181                                     state = 1 /* SawAsterisk */;
25182                                     indent += 1;
25183                                     break;
25184                                 }
25185                             // record the * as a comment
25186                             // falls through
25187                             default:
25188                                 if (state !== 3 /* SavingBackticks */) {
25189                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25190                                 }
25191                                 pushComment(scanner.getTokenText());
25192                                 break;
25193                         }
25194                         tok = nextTokenJSDoc();
25195                     }
25196                     removeLeadingNewlines(comments);
25197                     removeTrailingWhitespace(comments);
25198                     return comments.length === 0 ? undefined : comments.join("");
25199                 }
25200                 function parseUnknownTag(start, tagName) {
25201                     var result = createNode(306 /* JSDocTag */, start);
25202                     result.tagName = tagName;
25203                     return finishNode(result);
25204                 }
25205                 function addTag(tag) {
25206                     if (!tag) {
25207                         return;
25208                     }
25209                     if (!tags) {
25210                         tags = [tag];
25211                         tagsPos = tag.pos;
25212                     }
25213                     else {
25214                         tags.push(tag);
25215                     }
25216                     tagsEnd = tag.end;
25217                 }
25218                 function tryParseTypeExpression() {
25219                     skipWhitespaceOrAsterisk();
25220                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25221                 }
25222                 function parseBracketNameInPropertyAndParamTag() {
25223                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25224                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25225                     if (isBracketed) {
25226                         skipWhitespace();
25227                     }
25228                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25229                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25230                     var name = parseJSDocEntityName();
25231                     if (isBackquoted) {
25232                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25233                     }
25234                     if (isBracketed) {
25235                         skipWhitespace();
25236                         // May have an optional default, e.g. '[foo = 42]'
25237                         if (parseOptionalToken(62 /* EqualsToken */)) {
25238                             parseExpression();
25239                         }
25240                         parseExpected(23 /* CloseBracketToken */);
25241                     }
25242                     return { name: name, isBracketed: isBracketed };
25243                 }
25244                 function isObjectOrObjectArrayTypeReference(node) {
25245                     switch (node.kind) {
25246                         case 141 /* ObjectKeyword */:
25247                             return true;
25248                         case 174 /* ArrayType */:
25249                             return isObjectOrObjectArrayTypeReference(node.elementType);
25250                         default:
25251                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25252                     }
25253                 }
25254                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25255                     var typeExpression = tryParseTypeExpression();
25256                     var isNameFirst = !typeExpression;
25257                     skipWhitespaceOrAsterisk();
25258                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25259                     skipWhitespace();
25260                     if (isNameFirst) {
25261                         typeExpression = tryParseTypeExpression();
25262                     }
25263                     var result = target === 1 /* Property */ ?
25264                         createNode(323 /* JSDocPropertyTag */, start) :
25265                         createNode(317 /* JSDocParameterTag */, start);
25266                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25267                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25268                     if (nestedTypeLiteral) {
25269                         typeExpression = nestedTypeLiteral;
25270                         isNameFirst = true;
25271                     }
25272                     result.tagName = tagName;
25273                     result.typeExpression = typeExpression;
25274                     result.name = name;
25275                     result.isNameFirst = isNameFirst;
25276                     result.isBracketed = isBracketed;
25277                     result.comment = comment;
25278                     return finishNode(result);
25279                 }
25280                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25281                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25282                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25283                         var child = void 0;
25284                         var jsdocTypeLiteral = void 0;
25285                         var start_3 = scanner.getStartPos();
25286                         var children = void 0;
25287                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25288                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25289                                 children = ts.append(children, child);
25290                             }
25291                         }
25292                         if (children) {
25293                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25294                             jsdocTypeLiteral.jsDocPropertyTags = children;
25295                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25296                                 jsdocTypeLiteral.isArrayType = true;
25297                             }
25298                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25299                             return finishNode(typeLiteralExpression);
25300                         }
25301                     }
25302                 }
25303                 function parseReturnTag(start, tagName) {
25304                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25305                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25306                     }
25307                     var result = createNode(318 /* JSDocReturnTag */, start);
25308                     result.tagName = tagName;
25309                     result.typeExpression = tryParseTypeExpression();
25310                     return finishNode(result);
25311                 }
25312                 function parseTypeTag(start, tagName) {
25313                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25314                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25315                     }
25316                     var result = createNode(320 /* JSDocTypeTag */, start);
25317                     result.tagName = tagName;
25318                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25319                     return finishNode(result);
25320                 }
25321                 function parseAuthorTag(start, tagName, indent) {
25322                     var result = createNode(309 /* JSDocAuthorTag */, start);
25323                     result.tagName = tagName;
25324                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25325                     if (!authorInfoWithEmail) {
25326                         return finishNode(result);
25327                     }
25328                     result.comment = authorInfoWithEmail;
25329                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25330                         var comment = parseTagComments(indent);
25331                         if (comment) {
25332                             result.comment += comment;
25333                         }
25334                     }
25335                     return finishNode(result);
25336                 }
25337                 function tryParseAuthorNameAndEmail() {
25338                     var comments = [];
25339                     var seenLessThan = false;
25340                     var seenGreaterThan = false;
25341                     var token = scanner.getToken();
25342                     loop: while (true) {
25343                         switch (token) {
25344                             case 75 /* Identifier */:
25345                             case 5 /* WhitespaceTrivia */:
25346                             case 24 /* DotToken */:
25347                             case 59 /* AtToken */:
25348                                 comments.push(scanner.getTokenText());
25349                                 break;
25350                             case 29 /* LessThanToken */:
25351                                 if (seenLessThan || seenGreaterThan) {
25352                                     return;
25353                                 }
25354                                 seenLessThan = true;
25355                                 comments.push(scanner.getTokenText());
25356                                 break;
25357                             case 31 /* GreaterThanToken */:
25358                                 if (!seenLessThan || seenGreaterThan) {
25359                                     return;
25360                                 }
25361                                 seenGreaterThan = true;
25362                                 comments.push(scanner.getTokenText());
25363                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25364                                 break loop;
25365                             case 4 /* NewLineTrivia */:
25366                             case 1 /* EndOfFileToken */:
25367                                 break loop;
25368                         }
25369                         token = nextTokenJSDoc();
25370                     }
25371                     if (seenLessThan && seenGreaterThan) {
25372                         return comments.length === 0 ? undefined : comments.join("");
25373                     }
25374                 }
25375                 function parseImplementsTag(start, tagName) {
25376                     var result = createNode(308 /* JSDocImplementsTag */, start);
25377                     result.tagName = tagName;
25378                     result.class = parseExpressionWithTypeArgumentsForAugments();
25379                     return finishNode(result);
25380                 }
25381                 function parseAugmentsTag(start, tagName) {
25382                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25383                     result.tagName = tagName;
25384                     result.class = parseExpressionWithTypeArgumentsForAugments();
25385                     return finishNode(result);
25386                 }
25387                 function parseExpressionWithTypeArgumentsForAugments() {
25388                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25389                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25390                     node.expression = parsePropertyAccessEntityNameExpression();
25391                     node.typeArguments = tryParseTypeArguments();
25392                     var res = finishNode(node);
25393                     if (usedBrace) {
25394                         parseExpected(19 /* CloseBraceToken */);
25395                     }
25396                     return res;
25397                 }
25398                 function parsePropertyAccessEntityNameExpression() {
25399                     var node = parseJSDocIdentifierName();
25400                     while (parseOptional(24 /* DotToken */)) {
25401                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25402                         prop.expression = node;
25403                         prop.name = parseJSDocIdentifierName();
25404                         node = finishNode(prop);
25405                     }
25406                     return node;
25407                 }
25408                 function parseSimpleTag(start, kind, tagName) {
25409                     var tag = createNode(kind, start);
25410                     tag.tagName = tagName;
25411                     return finishNode(tag);
25412                 }
25413                 function parseThisTag(start, tagName) {
25414                     var tag = createNode(319 /* JSDocThisTag */, start);
25415                     tag.tagName = tagName;
25416                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25417                     skipWhitespace();
25418                     return finishNode(tag);
25419                 }
25420                 function parseEnumTag(start, tagName) {
25421                     var tag = createNode(316 /* JSDocEnumTag */, start);
25422                     tag.tagName = tagName;
25423                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25424                     skipWhitespace();
25425                     return finishNode(tag);
25426                 }
25427                 function parseTypedefTag(start, tagName, indent) {
25428                     var typeExpression = tryParseTypeExpression();
25429                     skipWhitespaceOrAsterisk();
25430                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25431                     typedefTag.tagName = tagName;
25432                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25433                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25434                     skipWhitespace();
25435                     typedefTag.comment = parseTagComments(indent);
25436                     typedefTag.typeExpression = typeExpression;
25437                     var end;
25438                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25439                         var child = void 0;
25440                         var jsdocTypeLiteral = void 0;
25441                         var childTypeTag = void 0;
25442                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25443                             if (!jsdocTypeLiteral) {
25444                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25445                             }
25446                             if (child.kind === 320 /* JSDocTypeTag */) {
25447                                 if (childTypeTag) {
25448                                     break;
25449                                 }
25450                                 else {
25451                                     childTypeTag = child;
25452                                 }
25453                             }
25454                             else {
25455                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25456                             }
25457                         }
25458                         if (jsdocTypeLiteral) {
25459                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25460                                 jsdocTypeLiteral.isArrayType = true;
25461                             }
25462                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25463                                 childTypeTag.typeExpression :
25464                                 finishNode(jsdocTypeLiteral);
25465                             end = typedefTag.typeExpression.end;
25466                         }
25467                     }
25468                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25469                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25470                 }
25471                 function parseJSDocTypeNameWithNamespace(nested) {
25472                     var pos = scanner.getTokenPos();
25473                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25474                         return undefined;
25475                     }
25476                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25477                     if (parseOptional(24 /* DotToken */)) {
25478                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25479                         if (nested) {
25480                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25481                         }
25482                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25483                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25484                         return finishNode(jsDocNamespaceNode);
25485                     }
25486                     if (nested) {
25487                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25488                     }
25489                     return typeNameOrNamespaceName;
25490                 }
25491                 function parseCallbackTag(start, tagName, indent) {
25492                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25493                     callbackTag.tagName = tagName;
25494                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25495                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25496                     skipWhitespace();
25497                     callbackTag.comment = parseTagComments(indent);
25498                     var child;
25499                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25500                     jsdocSignature.parameters = [];
25501                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25502                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25503                     }
25504                     var returnTag = tryParse(function () {
25505                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25506                             var tag = parseTag(indent);
25507                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25508                                 return tag;
25509                             }
25510                         }
25511                     });
25512                     if (returnTag) {
25513                         jsdocSignature.type = returnTag;
25514                     }
25515                     callbackTag.typeExpression = finishNode(jsdocSignature);
25516                     return finishNode(callbackTag);
25517                 }
25518                 function getJSDocTypeAliasName(fullName) {
25519                     if (fullName) {
25520                         var rightNode = fullName;
25521                         while (true) {
25522                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25523                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25524                             }
25525                             rightNode = rightNode.body;
25526                         }
25527                     }
25528                 }
25529                 function escapedTextsEqual(a, b) {
25530                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25531                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25532                             a = a.left;
25533                             b = b.left;
25534                         }
25535                         else {
25536                             return false;
25537                         }
25538                     }
25539                     return a.escapedText === b.escapedText;
25540                 }
25541                 function parseChildPropertyTag(indent) {
25542                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25543                 }
25544                 function parseChildParameterOrPropertyTag(target, indent, name) {
25545                     var canParseTag = true;
25546                     var seenAsterisk = false;
25547                     while (true) {
25548                         switch (nextTokenJSDoc()) {
25549                             case 59 /* AtToken */:
25550                                 if (canParseTag) {
25551                                     var child = tryParseChildTag(target, indent);
25552                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25553                                         target !== 4 /* CallbackParameter */ &&
25554                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25555                                         return false;
25556                                     }
25557                                     return child;
25558                                 }
25559                                 seenAsterisk = false;
25560                                 break;
25561                             case 4 /* NewLineTrivia */:
25562                                 canParseTag = true;
25563                                 seenAsterisk = false;
25564                                 break;
25565                             case 41 /* AsteriskToken */:
25566                                 if (seenAsterisk) {
25567                                     canParseTag = false;
25568                                 }
25569                                 seenAsterisk = true;
25570                                 break;
25571                             case 75 /* Identifier */:
25572                                 canParseTag = false;
25573                                 break;
25574                             case 1 /* EndOfFileToken */:
25575                                 return false;
25576                         }
25577                     }
25578                 }
25579                 function tryParseChildTag(target, indent) {
25580                     ts.Debug.assert(token() === 59 /* AtToken */);
25581                     var start = scanner.getStartPos();
25582                     nextTokenJSDoc();
25583                     var tagName = parseJSDocIdentifierName();
25584                     skipWhitespace();
25585                     var t;
25586                     switch (tagName.escapedText) {
25587                         case "type":
25588                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25589                         case "prop":
25590                         case "property":
25591                             t = 1 /* Property */;
25592                             break;
25593                         case "arg":
25594                         case "argument":
25595                         case "param":
25596                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25597                             break;
25598                         default:
25599                             return false;
25600                     }
25601                     if (!(target & t)) {
25602                         return false;
25603                     }
25604                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25605                 }
25606                 function parseTemplateTag(start, tagName) {
25607                     // the template tag looks like '@template {Constraint} T,U,V'
25608                     var constraint;
25609                     if (token() === 18 /* OpenBraceToken */) {
25610                         constraint = parseJSDocTypeExpression();
25611                     }
25612                     var typeParameters = [];
25613                     var typeParametersPos = getNodePos();
25614                     do {
25615                         skipWhitespace();
25616                         var typeParameter = createNode(155 /* TypeParameter */);
25617                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25618                         finishNode(typeParameter);
25619                         skipWhitespaceOrAsterisk();
25620                         typeParameters.push(typeParameter);
25621                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25622                     var result = createNode(321 /* JSDocTemplateTag */, start);
25623                     result.tagName = tagName;
25624                     result.constraint = constraint;
25625                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25626                     finishNode(result);
25627                     return result;
25628                 }
25629                 function parseOptionalJsdoc(t) {
25630                     if (token() === t) {
25631                         nextTokenJSDoc();
25632                         return true;
25633                     }
25634                     return false;
25635                 }
25636                 function parseJSDocEntityName() {
25637                     var entity = parseJSDocIdentifierName();
25638                     if (parseOptional(22 /* OpenBracketToken */)) {
25639                         parseExpected(23 /* CloseBracketToken */);
25640                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25641                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25642                         // but it's not worth it to enforce that restriction.
25643                     }
25644                     while (parseOptional(24 /* DotToken */)) {
25645                         var name = parseJSDocIdentifierName();
25646                         if (parseOptional(22 /* OpenBracketToken */)) {
25647                             parseExpected(23 /* CloseBracketToken */);
25648                         }
25649                         entity = createQualifiedName(entity, name);
25650                     }
25651                     return entity;
25652                 }
25653                 function parseJSDocIdentifierName(message) {
25654                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25655                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25656                     }
25657                     identifierCount++;
25658                     var pos = scanner.getTokenPos();
25659                     var end = scanner.getTextPos();
25660                     var result = createNode(75 /* Identifier */, pos);
25661                     if (token() !== 75 /* Identifier */) {
25662                         result.originalKeywordKind = token();
25663                     }
25664                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25665                     finishNode(result, end);
25666                     nextTokenJSDoc();
25667                     return result;
25668                 }
25669             }
25670         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25671     })(Parser || (Parser = {}));
25672     var IncrementalParser;
25673     (function (IncrementalParser) {
25674         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25675             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25676             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25677             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25678                 // if the text didn't change, then we can just return our current source file as-is.
25679                 return sourceFile;
25680             }
25681             if (sourceFile.statements.length === 0) {
25682                 // If we don't have any statements in the current source file, then there's no real
25683                 // way to incrementally parse.  So just do a full parse instead.
25684                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25685             }
25686             // Make sure we're not trying to incrementally update a source file more than once.  Once
25687             // we do an update the original source file is considered unusable from that point onwards.
25688             //
25689             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25690             // tree and give them new positions and parents.  From that point on, trusting the old
25691             // tree at all is not possible as far too much of it may violate invariants.
25692             var incrementalSourceFile = sourceFile;
25693             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25694             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25695             var oldText = sourceFile.text;
25696             var syntaxCursor = createSyntaxCursor(sourceFile);
25697             // Make the actual change larger so that we know to reparse anything whose lookahead
25698             // might have intersected the change.
25699             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25700             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25701             // Ensure that extending the affected range only moved the start of the change range
25702             // earlier in the file.
25703             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25704             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25705             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25706             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25707             // positive (if the edit added characters), negative (if the edit deleted characters)
25708             // or zero (if this was a pure overwrite with nothing added/removed).
25709             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25710             // If we added or removed characters during the edit, then we need to go and adjust all
25711             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25712             // may move backward (if we deleted chars).
25713             //
25714             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25715             // to reuse are already at the appropriate position in the new text.  That way when we
25716             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25717             // it very easy to determine if we can reuse a node.  If the node's position is at where
25718             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25719             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25720             // us, then we'll need to skip it or crumble it as appropriate
25721             //
25722             // We will also adjust the positions of nodes that intersect the change range as well.
25723             // By doing this, we ensure that all the positions in the old tree are consistent, not
25724             // just the positions of nodes entirely before/after the change range.  By being
25725             // consistent, we can then easily map from positions to nodes in the old tree easily.
25726             //
25727             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25728             // that we cannot reuse these elements.
25729             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25730             // Now that we've set up our internal incremental state just proceed and parse the
25731             // source file in the normal fashion.  When possible the parser will retrieve and
25732             // reuse nodes from the old tree.
25733             //
25734             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25735             // parsing, we will be reusing nodes from the old tree, and placing it into new
25736             // parents.  If we don't set the parents now, we'll end up with an observably
25737             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25738             // will immediately bail out of walking any subtrees when we can see that their parents
25739             // are already correct.
25740             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25741             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25742             return result;
25743         }
25744         IncrementalParser.updateSourceFile = updateSourceFile;
25745         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25746             if (!oldDirectives)
25747                 return newDirectives;
25748             var commentDirectives;
25749             var addedNewlyScannedDirectives = false;
25750             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25751                 var directive = oldDirectives_1[_i];
25752                 var range = directive.range, type = directive.type;
25753                 // Range before the change
25754                 if (range.end < changeStart) {
25755                     commentDirectives = ts.append(commentDirectives, directive);
25756                 }
25757                 else if (range.pos > changeRangeOldEnd) {
25758                     addNewlyScannedDirectives();
25759                     // Node is entirely past the change range.  We need to move both its pos and
25760                     // end, forward or backward appropriately.
25761                     var updatedDirective = {
25762                         range: { pos: range.pos + delta, end: range.end + delta },
25763                         type: type
25764                     };
25765                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25766                     if (aggressiveChecks) {
25767                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25768                     }
25769                 }
25770                 // Ignore ranges that fall in change range
25771             }
25772             addNewlyScannedDirectives();
25773             return commentDirectives;
25774             function addNewlyScannedDirectives() {
25775                 if (addedNewlyScannedDirectives)
25776                     return;
25777                 addedNewlyScannedDirectives = true;
25778                 if (!commentDirectives) {
25779                     commentDirectives = newDirectives;
25780                 }
25781                 else if (newDirectives) {
25782                     commentDirectives.push.apply(commentDirectives, newDirectives);
25783                 }
25784             }
25785         }
25786         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25787             if (isArray) {
25788                 visitArray(element);
25789             }
25790             else {
25791                 visitNode(element);
25792             }
25793             return;
25794             function visitNode(node) {
25795                 var text = "";
25796                 if (aggressiveChecks && shouldCheckNode(node)) {
25797                     text = oldText.substring(node.pos, node.end);
25798                 }
25799                 // Ditch any existing LS children we may have created.  This way we can avoid
25800                 // moving them forward.
25801                 if (node._children) {
25802                     node._children = undefined;
25803                 }
25804                 node.pos += delta;
25805                 node.end += delta;
25806                 if (aggressiveChecks && shouldCheckNode(node)) {
25807                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25808                 }
25809                 forEachChild(node, visitNode, visitArray);
25810                 if (ts.hasJSDocNodes(node)) {
25811                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25812                         var jsDocComment = _a[_i];
25813                         visitNode(jsDocComment);
25814                     }
25815                 }
25816                 checkNodePositions(node, aggressiveChecks);
25817             }
25818             function visitArray(array) {
25819                 array._children = undefined;
25820                 array.pos += delta;
25821                 array.end += delta;
25822                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25823                     var node = array_8[_i];
25824                     visitNode(node);
25825                 }
25826             }
25827         }
25828         function shouldCheckNode(node) {
25829             switch (node.kind) {
25830                 case 10 /* StringLiteral */:
25831                 case 8 /* NumericLiteral */:
25832                 case 75 /* Identifier */:
25833                     return true;
25834             }
25835             return false;
25836         }
25837         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
25838             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
25839             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
25840             ts.Debug.assert(element.pos <= element.end);
25841             // We have an element that intersects the change range in some way.  It may have its
25842             // start, or its end (or both) in the changed range.  We want to adjust any part
25843             // that intersects such that the final tree is in a consistent state.  i.e. all
25844             // children have spans within the span of their parent, and all siblings are ordered
25845             // properly.
25846             // We may need to update both the 'pos' and the 'end' of the element.
25847             // If the 'pos' is before the start of the change, then we don't need to touch it.
25848             // If it isn't, then the 'pos' must be inside the change.  How we update it will
25849             // depend if delta is positive or negative. If delta is positive then we have
25850             // something like:
25851             //
25852             //  -------------------AAA-----------------
25853             //  -------------------BBBCCCCCCC-----------------
25854             //
25855             // In this case, we consider any node that started in the change range to still be
25856             // starting at the same position.
25857             //
25858             // however, if the delta is negative, then we instead have something like this:
25859             //
25860             //  -------------------XXXYYYYYYY-----------------
25861             //  -------------------ZZZ-----------------
25862             //
25863             // In this case, any element that started in the 'X' range will keep its position.
25864             // However any element that started after that will have their pos adjusted to be
25865             // at the end of the new range.  i.e. any node that started in the 'Y' range will
25866             // be adjusted to have their start at the end of the 'Z' range.
25867             //
25868             // The element will keep its position if possible.  Or Move backward to the new-end
25869             // if it's in the 'Y' range.
25870             element.pos = Math.min(element.pos, changeRangeNewEnd);
25871             // If the 'end' is after the change range, then we always adjust it by the delta
25872             // amount.  However, if the end is in the change range, then how we adjust it
25873             // will depend on if delta is positive or negative.  If delta is positive then we
25874             // have something like:
25875             //
25876             //  -------------------AAA-----------------
25877             //  -------------------BBBCCCCCCC-----------------
25878             //
25879             // In this case, we consider any node that ended inside the change range to keep its
25880             // end position.
25881             //
25882             // however, if the delta is negative, then we instead have something like this:
25883             //
25884             //  -------------------XXXYYYYYYY-----------------
25885             //  -------------------ZZZ-----------------
25886             //
25887             // In this case, any element that ended in the 'X' range will keep its position.
25888             // However any element that ended after that will have their pos adjusted to be
25889             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
25890             // be adjusted to have their end at the end of the 'Z' range.
25891             if (element.end >= changeRangeOldEnd) {
25892                 // Element ends after the change range.  Always adjust the end pos.
25893                 element.end += delta;
25894             }
25895             else {
25896                 // Element ends in the change range.  The element will keep its position if
25897                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
25898                 element.end = Math.min(element.end, changeRangeNewEnd);
25899             }
25900             ts.Debug.assert(element.pos <= element.end);
25901             if (element.parent) {
25902                 ts.Debug.assert(element.pos >= element.parent.pos);
25903                 ts.Debug.assert(element.end <= element.parent.end);
25904             }
25905         }
25906         function checkNodePositions(node, aggressiveChecks) {
25907             if (aggressiveChecks) {
25908                 var pos_2 = node.pos;
25909                 var visitNode_1 = function (child) {
25910                     ts.Debug.assert(child.pos >= pos_2);
25911                     pos_2 = child.end;
25912                 };
25913                 if (ts.hasJSDocNodes(node)) {
25914                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25915                         var jsDocComment = _a[_i];
25916                         visitNode_1(jsDocComment);
25917                     }
25918                 }
25919                 forEachChild(node, visitNode_1);
25920                 ts.Debug.assert(pos_2 <= node.end);
25921             }
25922         }
25923         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
25924             visitNode(sourceFile);
25925             return;
25926             function visitNode(child) {
25927                 ts.Debug.assert(child.pos <= child.end);
25928                 if (child.pos > changeRangeOldEnd) {
25929                     // Node is entirely past the change range.  We need to move both its pos and
25930                     // end, forward or backward appropriately.
25931                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
25932                     return;
25933                 }
25934                 // Check if the element intersects the change range.  If it does, then it is not
25935                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25936                 // be able to use.
25937                 var fullEnd = child.end;
25938                 if (fullEnd >= changeStart) {
25939                     child.intersectsChange = true;
25940                     child._children = undefined;
25941                     // Adjust the pos or end (or both) of the intersecting element accordingly.
25942                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25943                     forEachChild(child, visitNode, visitArray);
25944                     if (ts.hasJSDocNodes(child)) {
25945                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
25946                             var jsDocComment = _a[_i];
25947                             visitNode(jsDocComment);
25948                         }
25949                     }
25950                     checkNodePositions(child, aggressiveChecks);
25951                     return;
25952                 }
25953                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
25954                 ts.Debug.assert(fullEnd < changeStart);
25955             }
25956             function visitArray(array) {
25957                 ts.Debug.assert(array.pos <= array.end);
25958                 if (array.pos > changeRangeOldEnd) {
25959                     // Array is entirely after the change range.  We need to move it, and move any of
25960                     // its children.
25961                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
25962                     return;
25963                 }
25964                 // Check if the element intersects the change range.  If it does, then it is not
25965                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25966                 // be able to use.
25967                 var fullEnd = array.end;
25968                 if (fullEnd >= changeStart) {
25969                     array.intersectsChange = true;
25970                     array._children = undefined;
25971                     // Adjust the pos or end (or both) of the intersecting array accordingly.
25972                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25973                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
25974                         var node = array_9[_i];
25975                         visitNode(node);
25976                     }
25977                     return;
25978                 }
25979                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
25980                 ts.Debug.assert(fullEnd < changeStart);
25981             }
25982         }
25983         function extendToAffectedRange(sourceFile, changeRange) {
25984             // Consider the following code:
25985             //      void foo() { /; }
25986             //
25987             // If the text changes with an insertion of / just before the semicolon then we end up with:
25988             //      void foo() { //; }
25989             //
25990             // If we were to just use the changeRange a is, then we would not rescan the { token
25991             // (as it does not intersect the actual original change range).  Because an edit may
25992             // change the token touching it, we actually need to look back *at least* one token so
25993             // that the prior token sees that change.
25994             var maxLookahead = 1;
25995             var start = changeRange.span.start;
25996             // the first iteration aligns us with the change start. subsequent iteration move us to
25997             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
25998             // start of the tree.
25999             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26000                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26001                 ts.Debug.assert(nearestNode.pos <= start);
26002                 var position = nearestNode.pos;
26003                 start = Math.max(0, position - 1);
26004             }
26005             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26006             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26007             return ts.createTextChangeRange(finalSpan, finalLength);
26008         }
26009         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26010             var bestResult = sourceFile;
26011             var lastNodeEntirelyBeforePosition;
26012             forEachChild(sourceFile, visit);
26013             if (lastNodeEntirelyBeforePosition) {
26014                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26015                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26016                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26017                 }
26018             }
26019             return bestResult;
26020             function getLastDescendant(node) {
26021                 while (true) {
26022                     var lastChild = ts.getLastChild(node);
26023                     if (lastChild) {
26024                         node = lastChild;
26025                     }
26026                     else {
26027                         return node;
26028                     }
26029                 }
26030             }
26031             function visit(child) {
26032                 if (ts.nodeIsMissing(child)) {
26033                     // Missing nodes are effectively invisible to us.  We never even consider them
26034                     // When trying to find the nearest node before us.
26035                     return;
26036                 }
26037                 // If the child intersects this position, then this node is currently the nearest
26038                 // node that starts before the position.
26039                 if (child.pos <= position) {
26040                     if (child.pos >= bestResult.pos) {
26041                         // This node starts before the position, and is closer to the position than
26042                         // the previous best node we found.  It is now the new best node.
26043                         bestResult = child;
26044                     }
26045                     // Now, the node may overlap the position, or it may end entirely before the
26046                     // position.  If it overlaps with the position, then either it, or one of its
26047                     // children must be the nearest node before the position.  So we can just
26048                     // recurse into this child to see if we can find something better.
26049                     if (position < child.end) {
26050                         // The nearest node is either this child, or one of the children inside
26051                         // of it.  We've already marked this child as the best so far.  Recurse
26052                         // in case one of the children is better.
26053                         forEachChild(child, visit);
26054                         // Once we look at the children of this node, then there's no need to
26055                         // continue any further.
26056                         return true;
26057                     }
26058                     else {
26059                         ts.Debug.assert(child.end <= position);
26060                         // The child ends entirely before this position.  Say you have the following
26061                         // (where $ is the position)
26062                         //
26063                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26064                         //
26065                         // We would want to find the nearest preceding node in "complex expr 2".
26066                         // To support that, we keep track of this node, and once we're done searching
26067                         // for a best node, we recurse down this node to see if we can find a good
26068                         // result in it.
26069                         //
26070                         // This approach allows us to quickly skip over nodes that are entirely
26071                         // before the position, while still allowing us to find any nodes in the
26072                         // last one that might be what we want.
26073                         lastNodeEntirelyBeforePosition = child;
26074                     }
26075                 }
26076                 else {
26077                     ts.Debug.assert(child.pos > position);
26078                     // We're now at a node that is entirely past the position we're searching for.
26079                     // This node (and all following nodes) could never contribute to the result,
26080                     // so just skip them by returning 'true' here.
26081                     return true;
26082                 }
26083             }
26084         }
26085         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26086             var oldText = sourceFile.text;
26087             if (textChangeRange) {
26088                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26089                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26090                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26091                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26092                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26093                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26094                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26095                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26096                 }
26097             }
26098         }
26099         function createSyntaxCursor(sourceFile) {
26100             var currentArray = sourceFile.statements;
26101             var currentArrayIndex = 0;
26102             ts.Debug.assert(currentArrayIndex < currentArray.length);
26103             var current = currentArray[currentArrayIndex];
26104             var lastQueriedPosition = -1 /* Value */;
26105             return {
26106                 currentNode: function (position) {
26107                     // Only compute the current node if the position is different than the last time
26108                     // we were asked.  The parser commonly asks for the node at the same position
26109                     // twice.  Once to know if can read an appropriate list element at a certain point,
26110                     // and then to actually read and consume the node.
26111                     if (position !== lastQueriedPosition) {
26112                         // Much of the time the parser will need the very next node in the array that
26113                         // we just returned a node from.So just simply check for that case and move
26114                         // forward in the array instead of searching for the node again.
26115                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26116                             currentArrayIndex++;
26117                             current = currentArray[currentArrayIndex];
26118                         }
26119                         // If we don't have a node, or the node we have isn't in the right position,
26120                         // then try to find a viable node at the position requested.
26121                         if (!current || current.pos !== position) {
26122                             findHighestListElementThatStartsAtPosition(position);
26123                         }
26124                     }
26125                     // Cache this query so that we don't do any extra work if the parser calls back
26126                     // into us.  Note: this is very common as the parser will make pairs of calls like
26127                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26128                     // called with 'isListElement', we don't want to redo the work when parseListElement
26129                     // is called immediately after.
26130                     lastQueriedPosition = position;
26131                     // Either we don'd have a node, or we have a node at the position being asked for.
26132                     ts.Debug.assert(!current || current.pos === position);
26133                     return current;
26134                 }
26135             };
26136             // Finds the highest element in the tree we can find that starts at the provided position.
26137             // The element must be a direct child of some node list in the tree.  This way after we
26138             // return it, we can easily return its next sibling in the list.
26139             function findHighestListElementThatStartsAtPosition(position) {
26140                 // Clear out any cached state about the last node we found.
26141                 currentArray = undefined;
26142                 currentArrayIndex = -1 /* Value */;
26143                 current = undefined;
26144                 // Recurse into the source file to find the highest node at this position.
26145                 forEachChild(sourceFile, visitNode, visitArray);
26146                 return;
26147                 function visitNode(node) {
26148                     if (position >= node.pos && position < node.end) {
26149                         // Position was within this node.  Keep searching deeper to find the node.
26150                         forEachChild(node, visitNode, visitArray);
26151                         // don't proceed any further in the search.
26152                         return true;
26153                     }
26154                     // position wasn't in this node, have to keep searching.
26155                     return false;
26156                 }
26157                 function visitArray(array) {
26158                     if (position >= array.pos && position < array.end) {
26159                         // position was in this array.  Search through this array to see if we find a
26160                         // viable element.
26161                         for (var i = 0; i < array.length; i++) {
26162                             var child = array[i];
26163                             if (child) {
26164                                 if (child.pos === position) {
26165                                     // Found the right node.  We're done.
26166                                     currentArray = array;
26167                                     currentArrayIndex = i;
26168                                     current = child;
26169                                     return true;
26170                                 }
26171                                 else {
26172                                     if (child.pos < position && position < child.end) {
26173                                         // Position in somewhere within this child.  Search in it and
26174                                         // stop searching in this array.
26175                                         forEachChild(child, visitNode, visitArray);
26176                                         return true;
26177                                     }
26178                                 }
26179                             }
26180                         }
26181                     }
26182                     // position wasn't in this array, have to keep searching.
26183                     return false;
26184                 }
26185             }
26186         }
26187         var InvalidPosition;
26188         (function (InvalidPosition) {
26189             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26190         })(InvalidPosition || (InvalidPosition = {}));
26191     })(IncrementalParser || (IncrementalParser = {}));
26192     /** @internal */
26193     function isDeclarationFileName(fileName) {
26194         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26195     }
26196     ts.isDeclarationFileName = isDeclarationFileName;
26197     /*@internal*/
26198     function processCommentPragmas(context, sourceText) {
26199         var pragmas = [];
26200         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26201             var range = _a[_i];
26202             var comment = sourceText.substring(range.pos, range.end);
26203             extractPragmas(pragmas, range, comment);
26204         }
26205         context.pragmas = ts.createMap();
26206         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26207             var pragma = pragmas_1[_b];
26208             if (context.pragmas.has(pragma.name)) {
26209                 var currentValue = context.pragmas.get(pragma.name);
26210                 if (currentValue instanceof Array) {
26211                     currentValue.push(pragma.args);
26212                 }
26213                 else {
26214                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26215                 }
26216                 continue;
26217             }
26218             context.pragmas.set(pragma.name, pragma.args);
26219         }
26220     }
26221     ts.processCommentPragmas = processCommentPragmas;
26222     /*@internal*/
26223     function processPragmasIntoFields(context, reportDiagnostic) {
26224         context.checkJsDirective = undefined;
26225         context.referencedFiles = [];
26226         context.typeReferenceDirectives = [];
26227         context.libReferenceDirectives = [];
26228         context.amdDependencies = [];
26229         context.hasNoDefaultLib = false;
26230         context.pragmas.forEach(function (entryOrList, key) {
26231             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26232             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26233             switch (key) {
26234                 case "reference": {
26235                     var referencedFiles_1 = context.referencedFiles;
26236                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26237                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26238                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26239                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26240                         if (arg.arguments["no-default-lib"]) {
26241                             context.hasNoDefaultLib = true;
26242                         }
26243                         else if (types) {
26244                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26245                         }
26246                         else if (lib) {
26247                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26248                         }
26249                         else if (path) {
26250                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26251                         }
26252                         else {
26253                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26254                         }
26255                     });
26256                     break;
26257                 }
26258                 case "amd-dependency": {
26259                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26260                     break;
26261                 }
26262                 case "amd-module": {
26263                     if (entryOrList instanceof Array) {
26264                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26265                             var entry = entryOrList_1[_i];
26266                             if (context.moduleName) {
26267                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26268                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26269                             }
26270                             context.moduleName = entry.arguments.name;
26271                         }
26272                     }
26273                     else {
26274                         context.moduleName = entryOrList.arguments.name;
26275                     }
26276                     break;
26277                 }
26278                 case "ts-nocheck":
26279                 case "ts-check": {
26280                     // _last_ of either nocheck or check in a file is the "winner"
26281                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26282                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26283                             context.checkJsDirective = {
26284                                 enabled: key === "ts-check",
26285                                 end: entry.range.end,
26286                                 pos: entry.range.pos
26287                             };
26288                         }
26289                     });
26290                     break;
26291                 }
26292                 case "jsx": return; // Accessed directly
26293                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26294             }
26295         });
26296     }
26297     ts.processPragmasIntoFields = processPragmasIntoFields;
26298     var namedArgRegExCache = ts.createMap();
26299     function getNamedArgRegEx(name) {
26300         if (namedArgRegExCache.has(name)) {
26301             return namedArgRegExCache.get(name);
26302         }
26303         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26304         namedArgRegExCache.set(name, result);
26305         return result;
26306     }
26307     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26308     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26309     function extractPragmas(pragmas, range, text) {
26310         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26311         if (tripleSlash) {
26312             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26313             var pragma = ts.commentPragmas[name];
26314             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26315                 return;
26316             }
26317             if (pragma.args) {
26318                 var argument = {};
26319                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26320                     var arg = _a[_i];
26321                     var matcher = getNamedArgRegEx(arg.name);
26322                     var matchResult = matcher.exec(text);
26323                     if (!matchResult && !arg.optional) {
26324                         return; // Missing required argument, don't parse
26325                     }
26326                     else if (matchResult) {
26327                         if (arg.captureSpan) {
26328                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26329                             argument[arg.name] = {
26330                                 value: matchResult[3],
26331                                 pos: startPos,
26332                                 end: startPos + matchResult[3].length
26333                             };
26334                         }
26335                         else {
26336                             argument[arg.name] = matchResult[3];
26337                         }
26338                     }
26339                 }
26340                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26341             }
26342             else {
26343                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26344             }
26345             return;
26346         }
26347         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26348         if (singleLine) {
26349             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26350         }
26351         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26352             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26353             var multiLineMatch = void 0;
26354             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26355                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26356             }
26357         }
26358     }
26359     function addPragmaForMatch(pragmas, range, kind, match) {
26360         if (!match)
26361             return;
26362         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26363         var pragma = ts.commentPragmas[name];
26364         if (!pragma || !(pragma.kind & kind)) {
26365             return;
26366         }
26367         var args = match[2]; // Split on spaces and match up positionally with definition
26368         var argument = getNamedPragmaArguments(pragma, args);
26369         if (argument === "fail")
26370             return; // Missing required argument, fail to parse it
26371         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26372         return;
26373     }
26374     function getNamedPragmaArguments(pragma, text) {
26375         if (!text)
26376             return {};
26377         if (!pragma.args)
26378             return {};
26379         var args = text.split(/\s+/);
26380         var argMap = {};
26381         for (var i = 0; i < pragma.args.length; i++) {
26382             var argument = pragma.args[i];
26383             if (!args[i] && !argument.optional) {
26384                 return "fail";
26385             }
26386             if (argument.captureSpan) {
26387                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26388             }
26389             argMap[argument.name] = args[i];
26390         }
26391         return argMap;
26392     }
26393     /** @internal */
26394     function tagNamesAreEquivalent(lhs, rhs) {
26395         if (lhs.kind !== rhs.kind) {
26396             return false;
26397         }
26398         if (lhs.kind === 75 /* Identifier */) {
26399             return lhs.escapedText === rhs.escapedText;
26400         }
26401         if (lhs.kind === 104 /* ThisKeyword */) {
26402             return true;
26403         }
26404         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26405         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26406         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26407         return lhs.name.escapedText === rhs.name.escapedText &&
26408             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26409     }
26410     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26411 })(ts || (ts = {}));
26412 var ts;
26413 (function (ts) {
26414     /* @internal */
26415     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26416     // NOTE: The order here is important to default lib ordering as entries will have the same
26417     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26418     //       order also affects overload resolution when a type declared in one lib is
26419     //       augmented in another lib.
26420     var libEntries = [
26421         // JavaScript only
26422         ["es5", "lib.es5.d.ts"],
26423         ["es6", "lib.es2015.d.ts"],
26424         ["es2015", "lib.es2015.d.ts"],
26425         ["es7", "lib.es2016.d.ts"],
26426         ["es2016", "lib.es2016.d.ts"],
26427         ["es2017", "lib.es2017.d.ts"],
26428         ["es2018", "lib.es2018.d.ts"],
26429         ["es2019", "lib.es2019.d.ts"],
26430         ["es2020", "lib.es2020.d.ts"],
26431         ["esnext", "lib.esnext.d.ts"],
26432         // Host only
26433         ["dom", "lib.dom.d.ts"],
26434         ["dom.iterable", "lib.dom.iterable.d.ts"],
26435         ["webworker", "lib.webworker.d.ts"],
26436         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26437         ["scripthost", "lib.scripthost.d.ts"],
26438         // ES2015 Or ESNext By-feature options
26439         ["es2015.core", "lib.es2015.core.d.ts"],
26440         ["es2015.collection", "lib.es2015.collection.d.ts"],
26441         ["es2015.generator", "lib.es2015.generator.d.ts"],
26442         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26443         ["es2015.promise", "lib.es2015.promise.d.ts"],
26444         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26445         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26446         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26447         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26448         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26449         ["es2017.object", "lib.es2017.object.d.ts"],
26450         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26451         ["es2017.string", "lib.es2017.string.d.ts"],
26452         ["es2017.intl", "lib.es2017.intl.d.ts"],
26453         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26454         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26455         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26456         ["es2018.intl", "lib.es2018.intl.d.ts"],
26457         ["es2018.promise", "lib.es2018.promise.d.ts"],
26458         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26459         ["es2019.array", "lib.es2019.array.d.ts"],
26460         ["es2019.object", "lib.es2019.object.d.ts"],
26461         ["es2019.string", "lib.es2019.string.d.ts"],
26462         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26463         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26464         ["es2020.promise", "lib.es2020.promise.d.ts"],
26465         ["es2020.string", "lib.es2020.string.d.ts"],
26466         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26467         ["esnext.array", "lib.es2019.array.d.ts"],
26468         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26469         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26470         ["esnext.intl", "lib.esnext.intl.d.ts"],
26471         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26472         ["esnext.string", "lib.esnext.string.d.ts"],
26473         ["esnext.promise", "lib.esnext.promise.d.ts"]
26474     ];
26475     /**
26476      * An array of supported "lib" reference file names used to determine the order for inclusion
26477      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26478      * overload resolution when a type declared in one lib is extended by another.
26479      */
26480     /* @internal */
26481     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26482     /**
26483      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26484      * option as well as for resolving lib reference directives.
26485      */
26486     /* @internal */
26487     ts.libMap = ts.createMapFromEntries(libEntries);
26488     // Watch related options
26489     /* @internal */
26490     ts.optionsForWatch = [
26491         {
26492             name: "watchFile",
26493             type: ts.createMapFromTemplate({
26494                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26495                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26496                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26497                 usefsevents: ts.WatchFileKind.UseFsEvents,
26498                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26499             }),
26500             category: ts.Diagnostics.Advanced_Options,
26501             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26502         },
26503         {
26504             name: "watchDirectory",
26505             type: ts.createMapFromTemplate({
26506                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26507                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26508                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26509             }),
26510             category: ts.Diagnostics.Advanced_Options,
26511             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26512         },
26513         {
26514             name: "fallbackPolling",
26515             type: ts.createMapFromTemplate({
26516                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26517                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26518                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26519             }),
26520             category: ts.Diagnostics.Advanced_Options,
26521             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26522         },
26523         {
26524             name: "synchronousWatchDirectory",
26525             type: "boolean",
26526             category: ts.Diagnostics.Advanced_Options,
26527             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26528         },
26529     ];
26530     /* @internal */
26531     ts.commonOptionsWithBuild = [
26532         {
26533             name: "help",
26534             shortName: "h",
26535             type: "boolean",
26536             showInSimplifiedHelpView: true,
26537             category: ts.Diagnostics.Command_line_Options,
26538             description: ts.Diagnostics.Print_this_message,
26539         },
26540         {
26541             name: "help",
26542             shortName: "?",
26543             type: "boolean"
26544         },
26545         {
26546             name: "watch",
26547             shortName: "w",
26548             type: "boolean",
26549             showInSimplifiedHelpView: true,
26550             category: ts.Diagnostics.Command_line_Options,
26551             description: ts.Diagnostics.Watch_input_files,
26552         },
26553         {
26554             name: "preserveWatchOutput",
26555             type: "boolean",
26556             showInSimplifiedHelpView: false,
26557             category: ts.Diagnostics.Command_line_Options,
26558             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26559         },
26560         {
26561             name: "listFiles",
26562             type: "boolean",
26563             category: ts.Diagnostics.Advanced_Options,
26564             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26565         },
26566         {
26567             name: "listEmittedFiles",
26568             type: "boolean",
26569             category: ts.Diagnostics.Advanced_Options,
26570             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26571         },
26572         {
26573             name: "pretty",
26574             type: "boolean",
26575             showInSimplifiedHelpView: true,
26576             category: ts.Diagnostics.Command_line_Options,
26577             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26578         },
26579         {
26580             name: "traceResolution",
26581             type: "boolean",
26582             category: ts.Diagnostics.Advanced_Options,
26583             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26584         },
26585         {
26586             name: "diagnostics",
26587             type: "boolean",
26588             category: ts.Diagnostics.Advanced_Options,
26589             description: ts.Diagnostics.Show_diagnostic_information
26590         },
26591         {
26592             name: "extendedDiagnostics",
26593             type: "boolean",
26594             category: ts.Diagnostics.Advanced_Options,
26595             description: ts.Diagnostics.Show_verbose_diagnostic_information
26596         },
26597         {
26598             name: "generateCpuProfile",
26599             type: "string",
26600             isFilePath: true,
26601             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26602             category: ts.Diagnostics.Advanced_Options,
26603             description: ts.Diagnostics.Generates_a_CPU_profile
26604         },
26605         {
26606             name: "incremental",
26607             shortName: "i",
26608             type: "boolean",
26609             category: ts.Diagnostics.Basic_Options,
26610             description: ts.Diagnostics.Enable_incremental_compilation,
26611             transpileOptionValue: undefined
26612         },
26613         {
26614             name: "assumeChangesOnlyAffectDirectDependencies",
26615             type: "boolean",
26616             affectsSemanticDiagnostics: true,
26617             affectsEmit: true,
26618             category: ts.Diagnostics.Advanced_Options,
26619             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26620         },
26621         {
26622             name: "locale",
26623             type: "string",
26624             category: ts.Diagnostics.Advanced_Options,
26625             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26626         },
26627     ];
26628     /* @internal */
26629     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26630         {
26631             name: "all",
26632             type: "boolean",
26633             showInSimplifiedHelpView: true,
26634             category: ts.Diagnostics.Command_line_Options,
26635             description: ts.Diagnostics.Show_all_compiler_options,
26636         },
26637         {
26638             name: "version",
26639             shortName: "v",
26640             type: "boolean",
26641             showInSimplifiedHelpView: true,
26642             category: ts.Diagnostics.Command_line_Options,
26643             description: ts.Diagnostics.Print_the_compiler_s_version,
26644         },
26645         {
26646             name: "init",
26647             type: "boolean",
26648             showInSimplifiedHelpView: true,
26649             category: ts.Diagnostics.Command_line_Options,
26650             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26651         },
26652         {
26653             name: "project",
26654             shortName: "p",
26655             type: "string",
26656             isFilePath: true,
26657             showInSimplifiedHelpView: true,
26658             category: ts.Diagnostics.Command_line_Options,
26659             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26660             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26661         },
26662         {
26663             name: "build",
26664             type: "boolean",
26665             shortName: "b",
26666             showInSimplifiedHelpView: true,
26667             category: ts.Diagnostics.Command_line_Options,
26668             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26669         },
26670         {
26671             name: "showConfig",
26672             type: "boolean",
26673             category: ts.Diagnostics.Command_line_Options,
26674             isCommandLineOnly: true,
26675             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26676         },
26677         {
26678             name: "listFilesOnly",
26679             type: "boolean",
26680             category: ts.Diagnostics.Command_line_Options,
26681             affectsSemanticDiagnostics: true,
26682             affectsEmit: true,
26683             isCommandLineOnly: true,
26684             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26685         },
26686         // Basic
26687         {
26688             name: "target",
26689             shortName: "t",
26690             type: ts.createMapFromTemplate({
26691                 es3: 0 /* ES3 */,
26692                 es5: 1 /* ES5 */,
26693                 es6: 2 /* ES2015 */,
26694                 es2015: 2 /* ES2015 */,
26695                 es2016: 3 /* ES2016 */,
26696                 es2017: 4 /* ES2017 */,
26697                 es2018: 5 /* ES2018 */,
26698                 es2019: 6 /* ES2019 */,
26699                 es2020: 7 /* ES2020 */,
26700                 esnext: 99 /* ESNext */,
26701             }),
26702             affectsSourceFile: true,
26703             affectsModuleResolution: true,
26704             affectsEmit: true,
26705             paramType: ts.Diagnostics.VERSION,
26706             showInSimplifiedHelpView: true,
26707             category: ts.Diagnostics.Basic_Options,
26708             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26709         },
26710         {
26711             name: "module",
26712             shortName: "m",
26713             type: ts.createMapFromTemplate({
26714                 none: ts.ModuleKind.None,
26715                 commonjs: ts.ModuleKind.CommonJS,
26716                 amd: ts.ModuleKind.AMD,
26717                 system: ts.ModuleKind.System,
26718                 umd: ts.ModuleKind.UMD,
26719                 es6: ts.ModuleKind.ES2015,
26720                 es2015: ts.ModuleKind.ES2015,
26721                 es2020: ts.ModuleKind.ES2020,
26722                 esnext: ts.ModuleKind.ESNext
26723             }),
26724             affectsModuleResolution: true,
26725             affectsEmit: true,
26726             paramType: ts.Diagnostics.KIND,
26727             showInSimplifiedHelpView: true,
26728             category: ts.Diagnostics.Basic_Options,
26729             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26730         },
26731         {
26732             name: "lib",
26733             type: "list",
26734             element: {
26735                 name: "lib",
26736                 type: ts.libMap
26737             },
26738             affectsModuleResolution: true,
26739             showInSimplifiedHelpView: true,
26740             category: ts.Diagnostics.Basic_Options,
26741             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26742             transpileOptionValue: undefined
26743         },
26744         {
26745             name: "allowJs",
26746             type: "boolean",
26747             affectsModuleResolution: true,
26748             showInSimplifiedHelpView: true,
26749             category: ts.Diagnostics.Basic_Options,
26750             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26751         },
26752         {
26753             name: "checkJs",
26754             type: "boolean",
26755             category: ts.Diagnostics.Basic_Options,
26756             description: ts.Diagnostics.Report_errors_in_js_files
26757         },
26758         {
26759             name: "jsx",
26760             type: ts.createMapFromTemplate({
26761                 "preserve": 1 /* Preserve */,
26762                 "react-native": 3 /* ReactNative */,
26763                 "react": 2 /* React */
26764             }),
26765             affectsSourceFile: true,
26766             paramType: ts.Diagnostics.KIND,
26767             showInSimplifiedHelpView: true,
26768             category: ts.Diagnostics.Basic_Options,
26769             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26770         },
26771         {
26772             name: "declaration",
26773             shortName: "d",
26774             type: "boolean",
26775             affectsEmit: true,
26776             showInSimplifiedHelpView: true,
26777             category: ts.Diagnostics.Basic_Options,
26778             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26779             transpileOptionValue: undefined
26780         },
26781         {
26782             name: "declarationMap",
26783             type: "boolean",
26784             affectsEmit: true,
26785             showInSimplifiedHelpView: true,
26786             category: ts.Diagnostics.Basic_Options,
26787             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26788             transpileOptionValue: undefined
26789         },
26790         {
26791             name: "emitDeclarationOnly",
26792             type: "boolean",
26793             affectsEmit: true,
26794             category: ts.Diagnostics.Advanced_Options,
26795             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26796             transpileOptionValue: undefined
26797         },
26798         {
26799             name: "sourceMap",
26800             type: "boolean",
26801             affectsEmit: true,
26802             showInSimplifiedHelpView: true,
26803             category: ts.Diagnostics.Basic_Options,
26804             description: ts.Diagnostics.Generates_corresponding_map_file,
26805         },
26806         {
26807             name: "outFile",
26808             type: "string",
26809             affectsEmit: true,
26810             isFilePath: true,
26811             paramType: ts.Diagnostics.FILE,
26812             showInSimplifiedHelpView: true,
26813             category: ts.Diagnostics.Basic_Options,
26814             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26815             transpileOptionValue: undefined
26816         },
26817         {
26818             name: "outDir",
26819             type: "string",
26820             affectsEmit: true,
26821             isFilePath: true,
26822             paramType: ts.Diagnostics.DIRECTORY,
26823             showInSimplifiedHelpView: true,
26824             category: ts.Diagnostics.Basic_Options,
26825             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26826         },
26827         {
26828             name: "rootDir",
26829             type: "string",
26830             affectsEmit: true,
26831             isFilePath: true,
26832             paramType: ts.Diagnostics.LOCATION,
26833             category: ts.Diagnostics.Basic_Options,
26834             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26835         },
26836         {
26837             name: "composite",
26838             type: "boolean",
26839             affectsEmit: true,
26840             isTSConfigOnly: true,
26841             category: ts.Diagnostics.Basic_Options,
26842             description: ts.Diagnostics.Enable_project_compilation,
26843             transpileOptionValue: undefined
26844         },
26845         {
26846             name: "tsBuildInfoFile",
26847             type: "string",
26848             affectsEmit: true,
26849             isFilePath: true,
26850             paramType: ts.Diagnostics.FILE,
26851             category: ts.Diagnostics.Basic_Options,
26852             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
26853             transpileOptionValue: undefined
26854         },
26855         {
26856             name: "removeComments",
26857             type: "boolean",
26858             affectsEmit: true,
26859             showInSimplifiedHelpView: true,
26860             category: ts.Diagnostics.Basic_Options,
26861             description: ts.Diagnostics.Do_not_emit_comments_to_output,
26862         },
26863         {
26864             name: "noEmit",
26865             type: "boolean",
26866             affectsEmit: true,
26867             showInSimplifiedHelpView: true,
26868             category: ts.Diagnostics.Basic_Options,
26869             description: ts.Diagnostics.Do_not_emit_outputs,
26870             transpileOptionValue: undefined
26871         },
26872         {
26873             name: "importHelpers",
26874             type: "boolean",
26875             affectsEmit: true,
26876             category: ts.Diagnostics.Basic_Options,
26877             description: ts.Diagnostics.Import_emit_helpers_from_tslib
26878         },
26879         {
26880             name: "importsNotUsedAsValues",
26881             type: ts.createMapFromTemplate({
26882                 remove: 0 /* Remove */,
26883                 preserve: 1 /* Preserve */,
26884                 error: 2 /* Error */
26885             }),
26886             affectsEmit: true,
26887             affectsSemanticDiagnostics: true,
26888             category: ts.Diagnostics.Advanced_Options,
26889             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
26890         },
26891         {
26892             name: "downlevelIteration",
26893             type: "boolean",
26894             affectsEmit: true,
26895             category: ts.Diagnostics.Basic_Options,
26896             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
26897         },
26898         {
26899             name: "isolatedModules",
26900             type: "boolean",
26901             category: ts.Diagnostics.Basic_Options,
26902             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
26903             transpileOptionValue: true
26904         },
26905         // Strict Type Checks
26906         {
26907             name: "strict",
26908             type: "boolean",
26909             showInSimplifiedHelpView: true,
26910             category: ts.Diagnostics.Strict_Type_Checking_Options,
26911             description: ts.Diagnostics.Enable_all_strict_type_checking_options
26912         },
26913         {
26914             name: "noImplicitAny",
26915             type: "boolean",
26916             affectsSemanticDiagnostics: true,
26917             strictFlag: true,
26918             showInSimplifiedHelpView: true,
26919             category: ts.Diagnostics.Strict_Type_Checking_Options,
26920             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
26921         },
26922         {
26923             name: "strictNullChecks",
26924             type: "boolean",
26925             affectsSemanticDiagnostics: true,
26926             strictFlag: true,
26927             showInSimplifiedHelpView: true,
26928             category: ts.Diagnostics.Strict_Type_Checking_Options,
26929             description: ts.Diagnostics.Enable_strict_null_checks
26930         },
26931         {
26932             name: "strictFunctionTypes",
26933             type: "boolean",
26934             affectsSemanticDiagnostics: true,
26935             strictFlag: true,
26936             showInSimplifiedHelpView: true,
26937             category: ts.Diagnostics.Strict_Type_Checking_Options,
26938             description: ts.Diagnostics.Enable_strict_checking_of_function_types
26939         },
26940         {
26941             name: "strictBindCallApply",
26942             type: "boolean",
26943             strictFlag: true,
26944             showInSimplifiedHelpView: true,
26945             category: ts.Diagnostics.Strict_Type_Checking_Options,
26946             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
26947         },
26948         {
26949             name: "strictPropertyInitialization",
26950             type: "boolean",
26951             affectsSemanticDiagnostics: true,
26952             strictFlag: true,
26953             showInSimplifiedHelpView: true,
26954             category: ts.Diagnostics.Strict_Type_Checking_Options,
26955             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
26956         },
26957         {
26958             name: "noImplicitThis",
26959             type: "boolean",
26960             affectsSemanticDiagnostics: true,
26961             strictFlag: true,
26962             showInSimplifiedHelpView: true,
26963             category: ts.Diagnostics.Strict_Type_Checking_Options,
26964             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
26965         },
26966         {
26967             name: "alwaysStrict",
26968             type: "boolean",
26969             affectsSourceFile: true,
26970             strictFlag: true,
26971             showInSimplifiedHelpView: true,
26972             category: ts.Diagnostics.Strict_Type_Checking_Options,
26973             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
26974         },
26975         // Additional Checks
26976         {
26977             name: "noUnusedLocals",
26978             type: "boolean",
26979             affectsSemanticDiagnostics: true,
26980             showInSimplifiedHelpView: true,
26981             category: ts.Diagnostics.Additional_Checks,
26982             description: ts.Diagnostics.Report_errors_on_unused_locals,
26983         },
26984         {
26985             name: "noUnusedParameters",
26986             type: "boolean",
26987             affectsSemanticDiagnostics: true,
26988             showInSimplifiedHelpView: true,
26989             category: ts.Diagnostics.Additional_Checks,
26990             description: ts.Diagnostics.Report_errors_on_unused_parameters,
26991         },
26992         {
26993             name: "noImplicitReturns",
26994             type: "boolean",
26995             affectsSemanticDiagnostics: true,
26996             showInSimplifiedHelpView: true,
26997             category: ts.Diagnostics.Additional_Checks,
26998             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
26999         },
27000         {
27001             name: "noFallthroughCasesInSwitch",
27002             type: "boolean",
27003             affectsBindDiagnostics: true,
27004             affectsSemanticDiagnostics: true,
27005             showInSimplifiedHelpView: true,
27006             category: ts.Diagnostics.Additional_Checks,
27007             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27008         },
27009         // Module Resolution
27010         {
27011             name: "moduleResolution",
27012             type: ts.createMapFromTemplate({
27013                 node: ts.ModuleResolutionKind.NodeJs,
27014                 classic: ts.ModuleResolutionKind.Classic,
27015             }),
27016             affectsModuleResolution: true,
27017             paramType: ts.Diagnostics.STRATEGY,
27018             category: ts.Diagnostics.Module_Resolution_Options,
27019             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27020         },
27021         {
27022             name: "baseUrl",
27023             type: "string",
27024             affectsModuleResolution: true,
27025             isFilePath: true,
27026             category: ts.Diagnostics.Module_Resolution_Options,
27027             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27028         },
27029         {
27030             // this option can only be specified in tsconfig.json
27031             // use type = object to copy the value as-is
27032             name: "paths",
27033             type: "object",
27034             affectsModuleResolution: true,
27035             isTSConfigOnly: true,
27036             category: ts.Diagnostics.Module_Resolution_Options,
27037             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27038             transpileOptionValue: undefined
27039         },
27040         {
27041             // this option can only be specified in tsconfig.json
27042             // use type = object to copy the value as-is
27043             name: "rootDirs",
27044             type: "list",
27045             isTSConfigOnly: true,
27046             element: {
27047                 name: "rootDirs",
27048                 type: "string",
27049                 isFilePath: true
27050             },
27051             affectsModuleResolution: true,
27052             category: ts.Diagnostics.Module_Resolution_Options,
27053             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27054             transpileOptionValue: undefined
27055         },
27056         {
27057             name: "typeRoots",
27058             type: "list",
27059             element: {
27060                 name: "typeRoots",
27061                 type: "string",
27062                 isFilePath: true
27063             },
27064             affectsModuleResolution: true,
27065             category: ts.Diagnostics.Module_Resolution_Options,
27066             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27067         },
27068         {
27069             name: "types",
27070             type: "list",
27071             element: {
27072                 name: "types",
27073                 type: "string"
27074             },
27075             affectsModuleResolution: true,
27076             showInSimplifiedHelpView: true,
27077             category: ts.Diagnostics.Module_Resolution_Options,
27078             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27079             transpileOptionValue: undefined
27080         },
27081         {
27082             name: "allowSyntheticDefaultImports",
27083             type: "boolean",
27084             affectsSemanticDiagnostics: true,
27085             category: ts.Diagnostics.Module_Resolution_Options,
27086             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27087         },
27088         {
27089             name: "esModuleInterop",
27090             type: "boolean",
27091             affectsSemanticDiagnostics: true,
27092             affectsEmit: true,
27093             showInSimplifiedHelpView: true,
27094             category: ts.Diagnostics.Module_Resolution_Options,
27095             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27096         },
27097         {
27098             name: "preserveSymlinks",
27099             type: "boolean",
27100             category: ts.Diagnostics.Module_Resolution_Options,
27101             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27102         },
27103         {
27104             name: "allowUmdGlobalAccess",
27105             type: "boolean",
27106             affectsSemanticDiagnostics: true,
27107             category: ts.Diagnostics.Module_Resolution_Options,
27108             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27109         },
27110         // Source Maps
27111         {
27112             name: "sourceRoot",
27113             type: "string",
27114             affectsEmit: true,
27115             paramType: ts.Diagnostics.LOCATION,
27116             category: ts.Diagnostics.Source_Map_Options,
27117             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27118         },
27119         {
27120             name: "mapRoot",
27121             type: "string",
27122             affectsEmit: true,
27123             paramType: ts.Diagnostics.LOCATION,
27124             category: ts.Diagnostics.Source_Map_Options,
27125             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27126         },
27127         {
27128             name: "inlineSourceMap",
27129             type: "boolean",
27130             affectsEmit: true,
27131             category: ts.Diagnostics.Source_Map_Options,
27132             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27133         },
27134         {
27135             name: "inlineSources",
27136             type: "boolean",
27137             affectsEmit: true,
27138             category: ts.Diagnostics.Source_Map_Options,
27139             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27140         },
27141         // Experimental
27142         {
27143             name: "experimentalDecorators",
27144             type: "boolean",
27145             affectsSemanticDiagnostics: true,
27146             category: ts.Diagnostics.Experimental_Options,
27147             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27148         },
27149         {
27150             name: "emitDecoratorMetadata",
27151             type: "boolean",
27152             affectsSemanticDiagnostics: true,
27153             affectsEmit: true,
27154             category: ts.Diagnostics.Experimental_Options,
27155             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27156         },
27157         // Advanced
27158         {
27159             name: "jsxFactory",
27160             type: "string",
27161             category: ts.Diagnostics.Advanced_Options,
27162             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27163         },
27164         {
27165             name: "resolveJsonModule",
27166             type: "boolean",
27167             affectsModuleResolution: true,
27168             category: ts.Diagnostics.Advanced_Options,
27169             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27170         },
27171         {
27172             name: "out",
27173             type: "string",
27174             affectsEmit: true,
27175             isFilePath: false,
27176             // for correct behaviour, please use outFile
27177             category: ts.Diagnostics.Advanced_Options,
27178             paramType: ts.Diagnostics.FILE,
27179             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27180             transpileOptionValue: undefined
27181         },
27182         {
27183             name: "reactNamespace",
27184             type: "string",
27185             affectsEmit: true,
27186             category: ts.Diagnostics.Advanced_Options,
27187             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27188         },
27189         {
27190             name: "skipDefaultLibCheck",
27191             type: "boolean",
27192             category: ts.Diagnostics.Advanced_Options,
27193             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27194         },
27195         {
27196             name: "charset",
27197             type: "string",
27198             category: ts.Diagnostics.Advanced_Options,
27199             description: ts.Diagnostics.The_character_set_of_the_input_files
27200         },
27201         {
27202             name: "emitBOM",
27203             type: "boolean",
27204             affectsEmit: true,
27205             category: ts.Diagnostics.Advanced_Options,
27206             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27207         },
27208         {
27209             name: "newLine",
27210             type: ts.createMapFromTemplate({
27211                 crlf: 0 /* CarriageReturnLineFeed */,
27212                 lf: 1 /* LineFeed */
27213             }),
27214             affectsEmit: true,
27215             paramType: ts.Diagnostics.NEWLINE,
27216             category: ts.Diagnostics.Advanced_Options,
27217             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27218         },
27219         {
27220             name: "noErrorTruncation",
27221             type: "boolean",
27222             affectsSemanticDiagnostics: true,
27223             category: ts.Diagnostics.Advanced_Options,
27224             description: ts.Diagnostics.Do_not_truncate_error_messages
27225         },
27226         {
27227             name: "noLib",
27228             type: "boolean",
27229             affectsModuleResolution: true,
27230             category: ts.Diagnostics.Advanced_Options,
27231             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27232             // We are not returning a sourceFile for lib file when asked by the program,
27233             // so pass --noLib to avoid reporting a file not found error.
27234             transpileOptionValue: true
27235         },
27236         {
27237             name: "noResolve",
27238             type: "boolean",
27239             affectsModuleResolution: true,
27240             category: ts.Diagnostics.Advanced_Options,
27241             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27242             // We are not doing a full typecheck, we are not resolving the whole context,
27243             // so pass --noResolve to avoid reporting missing file errors.
27244             transpileOptionValue: true
27245         },
27246         {
27247             name: "stripInternal",
27248             type: "boolean",
27249             affectsEmit: true,
27250             category: ts.Diagnostics.Advanced_Options,
27251             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27252         },
27253         {
27254             name: "disableSizeLimit",
27255             type: "boolean",
27256             affectsSourceFile: true,
27257             category: ts.Diagnostics.Advanced_Options,
27258             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27259         },
27260         {
27261             name: "disableSourceOfProjectReferenceRedirect",
27262             type: "boolean",
27263             isTSConfigOnly: true,
27264             category: ts.Diagnostics.Advanced_Options,
27265             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27266         },
27267         {
27268             name: "disableSolutionSearching",
27269             type: "boolean",
27270             isTSConfigOnly: true,
27271             category: ts.Diagnostics.Advanced_Options,
27272             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27273         },
27274         {
27275             name: "noImplicitUseStrict",
27276             type: "boolean",
27277             affectsSemanticDiagnostics: true,
27278             category: ts.Diagnostics.Advanced_Options,
27279             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27280         },
27281         {
27282             name: "noEmitHelpers",
27283             type: "boolean",
27284             affectsEmit: true,
27285             category: ts.Diagnostics.Advanced_Options,
27286             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27287         },
27288         {
27289             name: "noEmitOnError",
27290             type: "boolean",
27291             affectsEmit: true,
27292             category: ts.Diagnostics.Advanced_Options,
27293             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27294             transpileOptionValue: undefined
27295         },
27296         {
27297             name: "preserveConstEnums",
27298             type: "boolean",
27299             affectsEmit: true,
27300             category: ts.Diagnostics.Advanced_Options,
27301             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27302         },
27303         {
27304             name: "declarationDir",
27305             type: "string",
27306             affectsEmit: true,
27307             isFilePath: true,
27308             paramType: ts.Diagnostics.DIRECTORY,
27309             category: ts.Diagnostics.Advanced_Options,
27310             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27311             transpileOptionValue: undefined
27312         },
27313         {
27314             name: "skipLibCheck",
27315             type: "boolean",
27316             category: ts.Diagnostics.Advanced_Options,
27317             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27318         },
27319         {
27320             name: "allowUnusedLabels",
27321             type: "boolean",
27322             affectsBindDiagnostics: true,
27323             affectsSemanticDiagnostics: true,
27324             category: ts.Diagnostics.Advanced_Options,
27325             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27326         },
27327         {
27328             name: "allowUnreachableCode",
27329             type: "boolean",
27330             affectsBindDiagnostics: true,
27331             affectsSemanticDiagnostics: true,
27332             category: ts.Diagnostics.Advanced_Options,
27333             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27334         },
27335         {
27336             name: "suppressExcessPropertyErrors",
27337             type: "boolean",
27338             affectsSemanticDiagnostics: true,
27339             category: ts.Diagnostics.Advanced_Options,
27340             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27341         },
27342         {
27343             name: "suppressImplicitAnyIndexErrors",
27344             type: "boolean",
27345             affectsSemanticDiagnostics: true,
27346             category: ts.Diagnostics.Advanced_Options,
27347             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27348         },
27349         {
27350             name: "forceConsistentCasingInFileNames",
27351             type: "boolean",
27352             affectsModuleResolution: true,
27353             category: ts.Diagnostics.Advanced_Options,
27354             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27355         },
27356         {
27357             name: "maxNodeModuleJsDepth",
27358             type: "number",
27359             affectsModuleResolution: true,
27360             category: ts.Diagnostics.Advanced_Options,
27361             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27362         },
27363         {
27364             name: "noStrictGenericChecks",
27365             type: "boolean",
27366             affectsSemanticDiagnostics: true,
27367             category: ts.Diagnostics.Advanced_Options,
27368             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27369         },
27370         {
27371             name: "useDefineForClassFields",
27372             type: "boolean",
27373             affectsSemanticDiagnostics: true,
27374             affectsEmit: true,
27375             category: ts.Diagnostics.Advanced_Options,
27376             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27377         },
27378         {
27379             name: "keyofStringsOnly",
27380             type: "boolean",
27381             category: ts.Diagnostics.Advanced_Options,
27382             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27383         },
27384         {
27385             // A list of plugins to load in the language service
27386             name: "plugins",
27387             type: "list",
27388             isTSConfigOnly: true,
27389             element: {
27390                 name: "plugin",
27391                 type: "object"
27392             },
27393             description: ts.Diagnostics.List_of_language_service_plugins
27394         },
27395     ]);
27396     /* @internal */
27397     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27398     /* @internal */
27399     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27400     /* @internal */
27401     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27402     /* @internal */
27403     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27404         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27405     });
27406     /* @internal */
27407     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27408         return ts.hasProperty(option, "transpileOptionValue");
27409     });
27410     /* @internal */
27411     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27412         {
27413             name: "verbose",
27414             shortName: "v",
27415             category: ts.Diagnostics.Command_line_Options,
27416             description: ts.Diagnostics.Enable_verbose_logging,
27417             type: "boolean"
27418         },
27419         {
27420             name: "dry",
27421             shortName: "d",
27422             category: ts.Diagnostics.Command_line_Options,
27423             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27424             type: "boolean"
27425         },
27426         {
27427             name: "force",
27428             shortName: "f",
27429             category: ts.Diagnostics.Command_line_Options,
27430             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27431             type: "boolean"
27432         },
27433         {
27434             name: "clean",
27435             category: ts.Diagnostics.Command_line_Options,
27436             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27437             type: "boolean"
27438         }
27439     ]);
27440     /* @internal */
27441     ts.typeAcquisitionDeclarations = [
27442         {
27443             /* @deprecated typingOptions.enableAutoDiscovery
27444              * Use typeAcquisition.enable instead.
27445              */
27446             name: "enableAutoDiscovery",
27447             type: "boolean",
27448         },
27449         {
27450             name: "enable",
27451             type: "boolean",
27452         },
27453         {
27454             name: "include",
27455             type: "list",
27456             element: {
27457                 name: "include",
27458                 type: "string"
27459             }
27460         },
27461         {
27462             name: "exclude",
27463             type: "list",
27464             element: {
27465                 name: "exclude",
27466                 type: "string"
27467             }
27468         }
27469     ];
27470     /*@internal*/
27471     function createOptionNameMap(optionDeclarations) {
27472         var optionsNameMap = ts.createMap();
27473         var shortOptionNames = ts.createMap();
27474         ts.forEach(optionDeclarations, function (option) {
27475             optionsNameMap.set(option.name.toLowerCase(), option);
27476             if (option.shortName) {
27477                 shortOptionNames.set(option.shortName, option.name);
27478             }
27479         });
27480         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27481     }
27482     ts.createOptionNameMap = createOptionNameMap;
27483     var optionsNameMapCache;
27484     /* @internal */
27485     function getOptionsNameMap() {
27486         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27487     }
27488     ts.getOptionsNameMap = getOptionsNameMap;
27489     /* @internal */
27490     ts.defaultInitCompilerOptions = {
27491         module: ts.ModuleKind.CommonJS,
27492         target: 1 /* ES5 */,
27493         strict: true,
27494         esModuleInterop: true,
27495         forceConsistentCasingInFileNames: true,
27496         skipLibCheck: true
27497     };
27498     /* @internal */
27499     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27500         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27501         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27502             return {
27503                 enable: typeAcquisition.enableAutoDiscovery,
27504                 include: typeAcquisition.include || [],
27505                 exclude: typeAcquisition.exclude || []
27506             };
27507         }
27508         return typeAcquisition;
27509     }
27510     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27511     /* @internal */
27512     function createCompilerDiagnosticForInvalidCustomType(opt) {
27513         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27514     }
27515     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27516     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27517         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27518         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27519     }
27520     /* @internal */
27521     function parseCustomTypeOption(opt, value, errors) {
27522         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27523     }
27524     ts.parseCustomTypeOption = parseCustomTypeOption;
27525     /* @internal */
27526     function parseListTypeOption(opt, value, errors) {
27527         if (value === void 0) { value = ""; }
27528         value = trimString(value);
27529         if (ts.startsWith(value, "-")) {
27530             return undefined;
27531         }
27532         if (value === "") {
27533             return [];
27534         }
27535         var values = value.split(",");
27536         switch (opt.element.type) {
27537             case "number":
27538                 return ts.map(values, parseInt);
27539             case "string":
27540                 return ts.map(values, function (v) { return v || ""; });
27541             default:
27542                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27543         }
27544     }
27545     ts.parseListTypeOption = parseListTypeOption;
27546     function getOptionName(option) {
27547         return option.name;
27548     }
27549     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27550         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27551         return possibleOption ?
27552             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27553             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27554     }
27555     /*@internal*/
27556     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27557         var options = {};
27558         var watchOptions;
27559         var fileNames = [];
27560         var errors = [];
27561         parseStrings(commandLine);
27562         return {
27563             options: options,
27564             watchOptions: watchOptions,
27565             fileNames: fileNames,
27566             errors: errors
27567         };
27568         function parseStrings(args) {
27569             var i = 0;
27570             while (i < args.length) {
27571                 var s = args[i];
27572                 i++;
27573                 if (s.charCodeAt(0) === 64 /* at */) {
27574                     parseResponseFile(s.slice(1));
27575                 }
27576                 else if (s.charCodeAt(0) === 45 /* minus */) {
27577                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27578                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27579                     if (opt) {
27580                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27581                     }
27582                     else {
27583                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27584                         if (watchOpt) {
27585                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27586                         }
27587                         else {
27588                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27589                         }
27590                     }
27591                 }
27592                 else {
27593                     fileNames.push(s);
27594                 }
27595             }
27596         }
27597         function parseResponseFile(fileName) {
27598             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27599             if (!ts.isString(text)) {
27600                 errors.push(text);
27601                 return;
27602             }
27603             var args = [];
27604             var pos = 0;
27605             while (true) {
27606                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27607                     pos++;
27608                 if (pos >= text.length)
27609                     break;
27610                 var start = pos;
27611                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27612                     pos++;
27613                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27614                         pos++;
27615                     if (pos < text.length) {
27616                         args.push(text.substring(start + 1, pos));
27617                         pos++;
27618                     }
27619                     else {
27620                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27621                     }
27622                 }
27623                 else {
27624                     while (text.charCodeAt(pos) > 32 /* space */)
27625                         pos++;
27626                     args.push(text.substring(start, pos));
27627                 }
27628             }
27629             parseStrings(args);
27630         }
27631     }
27632     ts.parseCommandLineWorker = parseCommandLineWorker;
27633     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27634         if (opt.isTSConfigOnly) {
27635             var optValue = args[i];
27636             if (optValue === "null") {
27637                 options[opt.name] = undefined;
27638                 i++;
27639             }
27640             else if (opt.type === "boolean") {
27641                 if (optValue === "false") {
27642                     options[opt.name] = false;
27643                     i++;
27644                 }
27645                 else {
27646                     if (optValue === "true")
27647                         i++;
27648                     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));
27649                 }
27650             }
27651             else {
27652                 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));
27653                 if (optValue && !ts.startsWith(optValue, "-"))
27654                     i++;
27655             }
27656         }
27657         else {
27658             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27659             if (!args[i] && opt.type !== "boolean") {
27660                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27661             }
27662             if (args[i] !== "null") {
27663                 switch (opt.type) {
27664                     case "number":
27665                         options[opt.name] = parseInt(args[i]);
27666                         i++;
27667                         break;
27668                     case "boolean":
27669                         // boolean flag has optional value true, false, others
27670                         var optValue = args[i];
27671                         options[opt.name] = optValue !== "false";
27672                         // consume next argument as boolean flag value
27673                         if (optValue === "false" || optValue === "true") {
27674                             i++;
27675                         }
27676                         break;
27677                     case "string":
27678                         options[opt.name] = args[i] || "";
27679                         i++;
27680                         break;
27681                     case "list":
27682                         var result = parseListTypeOption(opt, args[i], errors);
27683                         options[opt.name] = result || [];
27684                         if (result) {
27685                             i++;
27686                         }
27687                         break;
27688                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27689                     default:
27690                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27691                         i++;
27692                         break;
27693                 }
27694             }
27695             else {
27696                 options[opt.name] = undefined;
27697                 i++;
27698             }
27699         }
27700         return i;
27701     }
27702     /*@internal*/
27703     ts.compilerOptionsDidYouMeanDiagnostics = {
27704         getOptionsNameMap: getOptionsNameMap,
27705         optionDeclarations: ts.optionDeclarations,
27706         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27707         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27708         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27709     };
27710     function parseCommandLine(commandLine, readFile) {
27711         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27712     }
27713     ts.parseCommandLine = parseCommandLine;
27714     /** @internal */
27715     function getOptionFromName(optionName, allowShort) {
27716         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27717     }
27718     ts.getOptionFromName = getOptionFromName;
27719     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27720         if (allowShort === void 0) { allowShort = false; }
27721         optionName = optionName.toLowerCase();
27722         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27723         // Try to translate short option names to their full equivalents.
27724         if (allowShort) {
27725             var short = shortOptionNames.get(optionName);
27726             if (short !== undefined) {
27727                 optionName = short;
27728             }
27729         }
27730         return optionsNameMap.get(optionName);
27731     }
27732     var buildOptionsNameMapCache;
27733     function getBuildOptionsNameMap() {
27734         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27735     }
27736     var buildOptionsDidYouMeanDiagnostics = {
27737         getOptionsNameMap: getBuildOptionsNameMap,
27738         optionDeclarations: ts.buildOpts,
27739         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27740         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27741         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27742     };
27743     /*@internal*/
27744     function parseBuildCommand(args) {
27745         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27746         var buildOptions = options;
27747         if (projects.length === 0) {
27748             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27749             projects.push(".");
27750         }
27751         // Nonsensical combinations
27752         if (buildOptions.clean && buildOptions.force) {
27753             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27754         }
27755         if (buildOptions.clean && buildOptions.verbose) {
27756             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27757         }
27758         if (buildOptions.clean && buildOptions.watch) {
27759             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27760         }
27761         if (buildOptions.watch && buildOptions.dry) {
27762             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27763         }
27764         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27765     }
27766     ts.parseBuildCommand = parseBuildCommand;
27767     /* @internal */
27768     function getDiagnosticText(_message) {
27769         var _args = [];
27770         for (var _i = 1; _i < arguments.length; _i++) {
27771             _args[_i - 1] = arguments[_i];
27772         }
27773         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27774         return diagnostic.messageText;
27775     }
27776     ts.getDiagnosticText = getDiagnosticText;
27777     /**
27778      * Reads the config file, reports errors if any and exits if the config file cannot be found
27779      */
27780     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27781         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27782         if (!ts.isString(configFileText)) {
27783             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27784             return undefined;
27785         }
27786         var result = ts.parseJsonText(configFileName, configFileText);
27787         var cwd = host.getCurrentDirectory();
27788         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27789         result.resolvedPath = result.path;
27790         result.originalFileName = result.fileName;
27791         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27792         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27793     }
27794     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27795     /**
27796      * Read tsconfig.json file
27797      * @param fileName The path to the config file
27798      */
27799     function readConfigFile(fileName, readFile) {
27800         var textOrDiagnostic = tryReadFile(fileName, readFile);
27801         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27802     }
27803     ts.readConfigFile = readConfigFile;
27804     /**
27805      * Parse the text of the tsconfig.json file
27806      * @param fileName The path to the config file
27807      * @param jsonText The text of the config file
27808      */
27809     function parseConfigFileTextToJson(fileName, jsonText) {
27810         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27811         return {
27812             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27813             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27814         };
27815     }
27816     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27817     /**
27818      * Read tsconfig.json file
27819      * @param fileName The path to the config file
27820      */
27821     function readJsonConfigFile(fileName, readFile) {
27822         var textOrDiagnostic = tryReadFile(fileName, readFile);
27823         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27824     }
27825     ts.readJsonConfigFile = readJsonConfigFile;
27826     /*@internal*/
27827     function tryReadFile(fileName, readFile) {
27828         var text;
27829         try {
27830             text = readFile(fileName);
27831         }
27832         catch (e) {
27833             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27834         }
27835         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27836     }
27837     ts.tryReadFile = tryReadFile;
27838     function commandLineOptionsToMap(options) {
27839         return ts.arrayToMap(options, getOptionName);
27840     }
27841     var typeAcquisitionDidYouMeanDiagnostics = {
27842         optionDeclarations: ts.typeAcquisitionDeclarations,
27843         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
27844         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
27845     };
27846     var watchOptionsNameMapCache;
27847     function getWatchOptionsNameMap() {
27848         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
27849     }
27850     var watchOptionsDidYouMeanDiagnostics = {
27851         getOptionsNameMap: getWatchOptionsNameMap,
27852         optionDeclarations: ts.optionsForWatch,
27853         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
27854         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
27855         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
27856     };
27857     var commandLineCompilerOptionsMapCache;
27858     function getCommandLineCompilerOptionsMap() {
27859         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
27860     }
27861     var commandLineWatchOptionsMapCache;
27862     function getCommandLineWatchOptionsMap() {
27863         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
27864     }
27865     var commandLineTypeAcquisitionMapCache;
27866     function getCommandLineTypeAcquisitionMap() {
27867         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
27868     }
27869     var _tsconfigRootOptions;
27870     function getTsconfigRootOptionsMap() {
27871         if (_tsconfigRootOptions === undefined) {
27872             _tsconfigRootOptions = {
27873                 name: undefined,
27874                 type: "object",
27875                 elementOptions: commandLineOptionsToMap([
27876                     {
27877                         name: "compilerOptions",
27878                         type: "object",
27879                         elementOptions: getCommandLineCompilerOptionsMap(),
27880                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
27881                     },
27882                     {
27883                         name: "watchOptions",
27884                         type: "object",
27885                         elementOptions: getCommandLineWatchOptionsMap(),
27886                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
27887                     },
27888                     {
27889                         name: "typingOptions",
27890                         type: "object",
27891                         elementOptions: getCommandLineTypeAcquisitionMap(),
27892                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
27893                     },
27894                     {
27895                         name: "typeAcquisition",
27896                         type: "object",
27897                         elementOptions: getCommandLineTypeAcquisitionMap(),
27898                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
27899                     },
27900                     {
27901                         name: "extends",
27902                         type: "string"
27903                     },
27904                     {
27905                         name: "references",
27906                         type: "list",
27907                         element: {
27908                             name: "references",
27909                             type: "object"
27910                         }
27911                     },
27912                     {
27913                         name: "files",
27914                         type: "list",
27915                         element: {
27916                             name: "files",
27917                             type: "string"
27918                         }
27919                     },
27920                     {
27921                         name: "include",
27922                         type: "list",
27923                         element: {
27924                             name: "include",
27925                             type: "string"
27926                         }
27927                     },
27928                     {
27929                         name: "exclude",
27930                         type: "list",
27931                         element: {
27932                             name: "exclude",
27933                             type: "string"
27934                         }
27935                     },
27936                     ts.compileOnSaveCommandLineOption
27937                 ])
27938             };
27939         }
27940         return _tsconfigRootOptions;
27941     }
27942     /**
27943      * Convert the json syntax tree into the json value
27944      */
27945     function convertToObject(sourceFile, errors) {
27946         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27947     }
27948     ts.convertToObject = convertToObject;
27949     /**
27950      * Convert the json syntax tree into the json value and report errors
27951      * This returns the json value (apart from checking errors) only if returnValue provided is true.
27952      * Otherwise it just checks the errors and returns undefined
27953      */
27954     /*@internal*/
27955     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
27956         if (!sourceFile.statements.length) {
27957             return returnValue ? {} : undefined;
27958         }
27959         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
27960         function isRootOptionMap(knownOptions) {
27961             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
27962         }
27963         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
27964             var result = returnValue ? {} : undefined;
27965             var _loop_3 = function (element) {
27966                 if (element.kind !== 281 /* PropertyAssignment */) {
27967                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
27968                     return "continue";
27969                 }
27970                 if (element.questionToken) {
27971                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
27972                 }
27973                 if (!isDoubleQuotedString(element.name)) {
27974                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
27975                 }
27976                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
27977                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
27978                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
27979                 if (keyText && extraKeyDiagnostics && !option) {
27980                     if (knownOptions) {
27981                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
27982                     }
27983                     else {
27984                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
27985                     }
27986                 }
27987                 var value = convertPropertyValueToJson(element.initializer, option);
27988                 if (typeof keyText !== "undefined") {
27989                     if (returnValue) {
27990                         result[keyText] = value;
27991                     }
27992                     // Notify key value set, if user asked for it
27993                     if (jsonConversionNotifier &&
27994                         // Current callbacks are only on known parent option or if we are setting values in the root
27995                         (parentOption || isRootOptionMap(knownOptions))) {
27996                         var isValidOptionValue = isCompilerOptionsValue(option, value);
27997                         if (parentOption) {
27998                             if (isValidOptionValue) {
27999                                 // Notify option set in the parent if its a valid option value
28000                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28001                             }
28002                         }
28003                         else if (isRootOptionMap(knownOptions)) {
28004                             if (isValidOptionValue) {
28005                                 // Notify about the valid root key value being set
28006                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28007                             }
28008                             else if (!option) {
28009                                 // Notify about the unknown root key value being set
28010                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28011                             }
28012                         }
28013                     }
28014                 }
28015             };
28016             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28017                 var element = _a[_i];
28018                 _loop_3(element);
28019             }
28020             return result;
28021         }
28022         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28023             if (!returnValue) {
28024                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28025             }
28026             // Filter out invalid values
28027             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28028         }
28029         function convertPropertyValueToJson(valueExpression, option) {
28030             switch (valueExpression.kind) {
28031                 case 106 /* TrueKeyword */:
28032                     reportInvalidOptionValue(option && option.type !== "boolean");
28033                     return true;
28034                 case 91 /* FalseKeyword */:
28035                     reportInvalidOptionValue(option && option.type !== "boolean");
28036                     return false;
28037                 case 100 /* NullKeyword */:
28038                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28039                     return null; // eslint-disable-line no-null/no-null
28040                 case 10 /* StringLiteral */:
28041                     if (!isDoubleQuotedString(valueExpression)) {
28042                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28043                     }
28044                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28045                     var text = valueExpression.text;
28046                     if (option && !ts.isString(option.type)) {
28047                         var customOption = option;
28048                         // Validate custom option type
28049                         if (!customOption.type.has(text.toLowerCase())) {
28050                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28051                         }
28052                     }
28053                     return text;
28054                 case 8 /* NumericLiteral */:
28055                     reportInvalidOptionValue(option && option.type !== "number");
28056                     return Number(valueExpression.text);
28057                 case 207 /* PrefixUnaryExpression */:
28058                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28059                         break; // not valid JSON syntax
28060                     }
28061                     reportInvalidOptionValue(option && option.type !== "number");
28062                     return -Number(valueExpression.operand.text);
28063                 case 193 /* ObjectLiteralExpression */:
28064                     reportInvalidOptionValue(option && option.type !== "object");
28065                     var objectLiteralExpression = valueExpression;
28066                     // Currently having element option declaration in the tsconfig with type "object"
28067                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28068                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28069                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28070                     // vs what we set in the json
28071                     // If need arises, we can modify this interface and callbacks as needed
28072                     if (option) {
28073                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28074                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28075                     }
28076                     else {
28077                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28078                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28079                     }
28080                 case 192 /* ArrayLiteralExpression */:
28081                     reportInvalidOptionValue(option && option.type !== "list");
28082                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28083             }
28084             // Not in expected format
28085             if (option) {
28086                 reportInvalidOptionValue(/*isError*/ true);
28087             }
28088             else {
28089                 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));
28090             }
28091             return undefined;
28092             function reportInvalidOptionValue(isError) {
28093                 if (isError) {
28094                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28095                 }
28096             }
28097         }
28098         function isDoubleQuotedString(node) {
28099             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28100         }
28101     }
28102     ts.convertToObjectWorker = convertToObjectWorker;
28103     function getCompilerOptionValueTypeString(option) {
28104         return option.type === "list" ?
28105             "Array" :
28106             ts.isString(option.type) ? option.type : "string";
28107     }
28108     function isCompilerOptionsValue(option, value) {
28109         if (option) {
28110             if (isNullOrUndefined(value))
28111                 return true; // All options are undefinable/nullable
28112             if (option.type === "list") {
28113                 return ts.isArray(value);
28114             }
28115             var expectedType = ts.isString(option.type) ? option.type : "string";
28116             return typeof value === expectedType;
28117         }
28118         return false;
28119     }
28120     /**
28121      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28122      * @param configParseResult options to be generated into tsconfig.json
28123      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28124      * @param host provides current directory and case sensitivity services
28125      */
28126     /** @internal */
28127     function convertToTSConfig(configParseResult, configFileName, host) {
28128         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28129         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); });
28130         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28131         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28132         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 ? {
28133             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28134             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28135         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28136         return config;
28137     }
28138     ts.convertToTSConfig = convertToTSConfig;
28139     function optionMapToObject(optionMap) {
28140         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28141             var _a;
28142             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28143         }, {}));
28144     }
28145     function filterSameAsDefaultInclude(specs) {
28146         if (!ts.length(specs))
28147             return undefined;
28148         if (ts.length(specs) !== 1)
28149             return specs;
28150         if (specs[0] === "**/*")
28151             return undefined;
28152         return specs;
28153     }
28154     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28155         if (!includeSpecs)
28156             return function (_) { return true; };
28157         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28158         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28159         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28160         if (includeRe) {
28161             if (excludeRe) {
28162                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28163             }
28164             return function (path) { return !includeRe.test(path); };
28165         }
28166         if (excludeRe) {
28167             return function (path) { return excludeRe.test(path); };
28168         }
28169         return function (_) { return true; };
28170     }
28171     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28172         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28173             // this is of a type CommandLineOptionOfPrimitiveType
28174             return undefined;
28175         }
28176         else if (optionDefinition.type === "list") {
28177             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28178         }
28179         else {
28180             return optionDefinition.type;
28181         }
28182     }
28183     function getNameOfCompilerOptionValue(value, customTypeMap) {
28184         // There is a typeMap associated with this command-line option so use it to map value back to its name
28185         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28186             if (mapValue === value) {
28187                 return key;
28188             }
28189         });
28190     }
28191     function serializeCompilerOptions(options, pathOptions) {
28192         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28193     }
28194     function serializeWatchOptions(options) {
28195         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28196     }
28197     function serializeOptionBaseObject(options, _a, pathOptions) {
28198         var optionsNameMap = _a.optionsNameMap;
28199         var result = ts.createMap();
28200         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28201         var _loop_4 = function (name) {
28202             if (ts.hasProperty(options, name)) {
28203                 // tsconfig only options cannot be specified via command line,
28204                 // so we can assume that only types that can appear here string | number | boolean
28205                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28206                     return "continue";
28207                 }
28208                 var value = options[name];
28209                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28210                 if (optionDefinition) {
28211                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28212                     if (!customTypeMap_1) {
28213                         // There is no map associated with this compiler option then use the value as-is
28214                         // This is the case if the value is expect to be string, number, boolean or list of string
28215                         if (pathOptions && optionDefinition.isFilePath) {
28216                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28217                         }
28218                         else {
28219                             result.set(name, value);
28220                         }
28221                     }
28222                     else {
28223                         if (optionDefinition.type === "list") {
28224                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28225                         }
28226                         else {
28227                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28228                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28229                         }
28230                     }
28231                 }
28232             }
28233         };
28234         for (var name in options) {
28235             _loop_4(name);
28236         }
28237         return result;
28238     }
28239     /**
28240      * Generate tsconfig configuration when running command line "--init"
28241      * @param options commandlineOptions to be generated into tsconfig.json
28242      * @param fileNames array of filenames to be generated into tsconfig.json
28243      */
28244     /* @internal */
28245     function generateTSConfig(options, fileNames, newLine) {
28246         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28247         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28248         return writeConfigurations();
28249         function getDefaultValueForOption(option) {
28250             switch (option.type) {
28251                 case "number":
28252                     return 1;
28253                 case "boolean":
28254                     return true;
28255                 case "string":
28256                     return option.isFilePath ? "./" : "";
28257                 case "list":
28258                     return [];
28259                 case "object":
28260                     return {};
28261                 default:
28262                     var iterResult = option.type.keys().next();
28263                     if (!iterResult.done)
28264                         return iterResult.value;
28265                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28266             }
28267         }
28268         function makePadding(paddingLength) {
28269             return Array(paddingLength + 1).join(" ");
28270         }
28271         function isAllowedOption(_a) {
28272             var category = _a.category, name = _a.name;
28273             // Skip options which do not have a category or have category `Command_line_Options`
28274             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28275             return category !== undefined
28276                 && category !== ts.Diagnostics.Command_line_Options
28277                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28278         }
28279         function writeConfigurations() {
28280             // Filter applicable options to place in the file
28281             var categorizedOptions = ts.createMultiMap();
28282             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28283                 var option = optionDeclarations_1[_i];
28284                 var category = option.category;
28285                 if (isAllowedOption(option)) {
28286                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28287                 }
28288             }
28289             // Serialize all options and their descriptions
28290             var marginLength = 0;
28291             var seenKnownKeys = 0;
28292             var entries = [];
28293             categorizedOptions.forEach(function (options, category) {
28294                 if (entries.length !== 0) {
28295                     entries.push({ value: "" });
28296                 }
28297                 entries.push({ value: "/* " + category + " */" });
28298                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28299                     var option = options_1[_i];
28300                     var optionName = void 0;
28301                     if (compilerOptionsMap.has(option.name)) {
28302                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28303                     }
28304                     else {
28305                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28306                     }
28307                     entries.push({
28308                         value: optionName,
28309                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28310                     });
28311                     marginLength = Math.max(optionName.length, marginLength);
28312                 }
28313             });
28314             // Write the output
28315             var tab = makePadding(2);
28316             var result = [];
28317             result.push("{");
28318             result.push(tab + "\"compilerOptions\": {");
28319             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28320             result.push("");
28321             // Print out each row, aligning all the descriptions on the same column.
28322             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28323                 var entry = entries_3[_a];
28324                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28325                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28326             }
28327             if (fileNames.length) {
28328                 result.push(tab + "},");
28329                 result.push(tab + "\"files\": [");
28330                 for (var i = 0; i < fileNames.length; i++) {
28331                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28332                 }
28333                 result.push(tab + "]");
28334             }
28335             else {
28336                 result.push(tab + "}");
28337             }
28338             result.push("}");
28339             return result.join(newLine) + newLine;
28340         }
28341     }
28342     ts.generateTSConfig = generateTSConfig;
28343     /* @internal */
28344     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28345         var result = {};
28346         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28347         for (var name in options) {
28348             if (ts.hasProperty(options, name)) {
28349                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28350             }
28351         }
28352         if (result.configFilePath) {
28353             result.configFilePath = toAbsolutePath(result.configFilePath);
28354         }
28355         return result;
28356     }
28357     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28358     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28359         if (option && !isNullOrUndefined(value)) {
28360             if (option.type === "list") {
28361                 var values = value;
28362                 if (option.element.isFilePath && values.length) {
28363                     return values.map(toAbsolutePath);
28364                 }
28365             }
28366             else if (option.isFilePath) {
28367                 return toAbsolutePath(value);
28368             }
28369         }
28370         return value;
28371     }
28372     /**
28373      * Parse the contents of a config file (tsconfig.json).
28374      * @param json The contents of the config file to parse
28375      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28376      * @param basePath A root directory to resolve relative path entries in the config
28377      *    file to. e.g. outDir
28378      */
28379     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28380         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28381     }
28382     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28383     /**
28384      * Parse the contents of a config file (tsconfig.json).
28385      * @param jsonNode The contents of the config file to parse
28386      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28387      * @param basePath A root directory to resolve relative path entries in the config
28388      *    file to. e.g. outDir
28389      */
28390     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28391         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28392     }
28393     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28394     /*@internal*/
28395     function setConfigFileInOptions(options, configFile) {
28396         if (configFile) {
28397             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28398         }
28399     }
28400     ts.setConfigFileInOptions = setConfigFileInOptions;
28401     function isNullOrUndefined(x) {
28402         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28403     }
28404     function directoryOfCombinedPath(fileName, basePath) {
28405         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28406         // until consistent casing errors are reported
28407         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28408     }
28409     /**
28410      * Parse the contents of a config file from json or json source file (tsconfig.json).
28411      * @param json The contents of the config file to parse
28412      * @param sourceFile sourceFile corresponding to the Json
28413      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28414      * @param basePath A root directory to resolve relative path entries in the config
28415      *    file to. e.g. outDir
28416      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28417      */
28418     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28419         if (existingOptions === void 0) { existingOptions = {}; }
28420         if (resolutionStack === void 0) { resolutionStack = []; }
28421         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28422         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28423         var errors = [];
28424         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28425         var raw = parsedConfig.raw;
28426         var options = ts.extend(existingOptions, parsedConfig.options || {});
28427         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28428             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28429             parsedConfig.watchOptions || existingWatchOptions;
28430         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28431         setConfigFileInOptions(options, sourceFile);
28432         var projectReferences;
28433         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28434         return {
28435             options: options,
28436             watchOptions: watchOptions,
28437             fileNames: fileNames,
28438             projectReferences: projectReferences,
28439             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28440             raw: raw,
28441             errors: errors,
28442             wildcardDirectories: wildcardDirectories,
28443             compileOnSave: !!raw.compileOnSave,
28444             configFileSpecs: spec
28445         };
28446         function getFileNames() {
28447             var filesSpecs;
28448             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28449                 if (ts.isArray(raw.files)) {
28450                     filesSpecs = raw.files;
28451                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28452                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28453                     var hasExtends = ts.hasProperty(raw, "extends");
28454                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28455                         if (sourceFile) {
28456                             var fileName = configFileName || "tsconfig.json";
28457                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28458                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28459                             var error = nodeValue
28460                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28461                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28462                             errors.push(error);
28463                         }
28464                         else {
28465                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28466                         }
28467                     }
28468                 }
28469                 else {
28470                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28471                 }
28472             }
28473             var includeSpecs;
28474             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28475                 if (ts.isArray(raw.include)) {
28476                     includeSpecs = raw.include;
28477                 }
28478                 else {
28479                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28480                 }
28481             }
28482             var excludeSpecs;
28483             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28484                 if (ts.isArray(raw.exclude)) {
28485                     excludeSpecs = raw.exclude;
28486                 }
28487                 else {
28488                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28489                 }
28490             }
28491             else if (raw.compilerOptions) {
28492                 var outDir = raw.compilerOptions.outDir;
28493                 var declarationDir = raw.compilerOptions.declarationDir;
28494                 if (outDir || declarationDir) {
28495                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28496                 }
28497             }
28498             if (filesSpecs === undefined && includeSpecs === undefined) {
28499                 includeSpecs = ["**/*"];
28500             }
28501             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28502             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28503                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28504             }
28505             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28506                 if (ts.isArray(raw.references)) {
28507                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28508                         var ref = _a[_i];
28509                         if (typeof ref.path !== "string") {
28510                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28511                         }
28512                         else {
28513                             (projectReferences || (projectReferences = [])).push({
28514                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28515                                 originalPath: ref.path,
28516                                 prepend: ref.prepend,
28517                                 circular: ref.circular
28518                             });
28519                         }
28520                     }
28521                 }
28522                 else {
28523                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28524                 }
28525             }
28526             return result;
28527         }
28528         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28529             if (!sourceFile) {
28530                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28531             }
28532         }
28533     }
28534     function isErrorNoInputFiles(error) {
28535         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28536     }
28537     function getErrorForNoInputFiles(_a, configFileName) {
28538         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28539         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 || []));
28540     }
28541     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28542         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28543     }
28544     /*@internal*/
28545     function canJsonReportNoInutFiles(raw) {
28546         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28547     }
28548     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28549     /*@internal*/
28550     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28551         var existingErrors = configParseDiagnostics.length;
28552         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28553             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28554         }
28555         else {
28556             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28557         }
28558         return existingErrors !== configParseDiagnostics.length;
28559     }
28560     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28561     function isSuccessfulParsedTsconfig(value) {
28562         return !!value.options;
28563     }
28564     /**
28565      * This *just* extracts options/include/exclude/files out of a config file.
28566      * It does *not* resolve the included files.
28567      */
28568     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28569         basePath = ts.normalizeSlashes(basePath);
28570         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28571         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28572             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28573             return { raw: json || convertToObject(sourceFile, errors) };
28574         }
28575         var ownConfig = json ?
28576             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28577             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28578         if (ownConfig.extendedConfigPath) {
28579             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28580             resolutionStack = resolutionStack.concat([resolvedPath]);
28581             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28582             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28583                 var baseRaw_1 = extendedConfig.raw;
28584                 var raw_1 = ownConfig.raw;
28585                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28586                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28587                     if (value) {
28588                         raw_1[propertyName] = value;
28589                     }
28590                 };
28591                 setPropertyInRawIfNotUndefined("include");
28592                 setPropertyInRawIfNotUndefined("exclude");
28593                 setPropertyInRawIfNotUndefined("files");
28594                 if (raw_1.compileOnSave === undefined) {
28595                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28596                 }
28597                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28598                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28599                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28600                     ownConfig.watchOptions || extendedConfig.watchOptions;
28601                 // TODO extend type typeAcquisition
28602             }
28603         }
28604         return ownConfig;
28605     }
28606     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28607         if (ts.hasProperty(json, "excludes")) {
28608             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28609         }
28610         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28611         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28612         // It should be removed in future releases - use typeAcquisition instead.
28613         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28614         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28615         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28616         var extendedConfigPath;
28617         if (json.extends) {
28618             if (!ts.isString(json.extends)) {
28619                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28620             }
28621             else {
28622                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28623                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28624             }
28625         }
28626         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28627     }
28628     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28629         var options = getDefaultCompilerOptions(configFileName);
28630         var typeAcquisition, typingOptionstypeAcquisition;
28631         var watchOptions;
28632         var extendedConfigPath;
28633         var optionsIterator = {
28634             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28635                 var currentOption;
28636                 switch (parentOption) {
28637                     case "compilerOptions":
28638                         currentOption = options;
28639                         break;
28640                     case "watchOptions":
28641                         currentOption = (watchOptions || (watchOptions = {}));
28642                         break;
28643                     case "typeAcquisition":
28644                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28645                         break;
28646                     case "typingOptions":
28647                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28648                         break;
28649                     default:
28650                         ts.Debug.fail("Unknown option");
28651                 }
28652                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28653             },
28654             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28655                 switch (key) {
28656                     case "extends":
28657                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28658                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28659                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28660                         });
28661                         return;
28662                 }
28663             },
28664             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28665                 if (key === "excludes") {
28666                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28667                 }
28668             }
28669         };
28670         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28671         if (!typeAcquisition) {
28672             if (typingOptionstypeAcquisition) {
28673                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28674                     {
28675                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28676                         include: typingOptionstypeAcquisition.include,
28677                         exclude: typingOptionstypeAcquisition.exclude
28678                     } :
28679                     typingOptionstypeAcquisition;
28680             }
28681             else {
28682                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28683             }
28684         }
28685         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28686     }
28687     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28688         extendedConfig = ts.normalizeSlashes(extendedConfig);
28689         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28690             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28691             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28692                 extendedConfigPath = extendedConfigPath + ".json";
28693                 if (!host.fileExists(extendedConfigPath)) {
28694                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28695                     return undefined;
28696                 }
28697             }
28698             return extendedConfigPath;
28699         }
28700         // If the path isn't a rooted or relative path, resolve like a module
28701         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28702         if (resolved.resolvedModule) {
28703             return resolved.resolvedModule.resolvedFileName;
28704         }
28705         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28706         return undefined;
28707     }
28708     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28709         var _a;
28710         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28711         var value;
28712         var extendedResult;
28713         var extendedConfig;
28714         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28715             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28716         }
28717         else {
28718             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28719             if (!extendedResult.parseDiagnostics.length) {
28720                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28721                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28722                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28723                     // Update the paths to reflect base path
28724                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28725                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28726                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28727                         if (raw_2[propertyName]) {
28728                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28729                         }
28730                     };
28731                     var raw_2 = extendedConfig.raw;
28732                     mapPropertiesInRawIfNotUndefined("include");
28733                     mapPropertiesInRawIfNotUndefined("exclude");
28734                     mapPropertiesInRawIfNotUndefined("files");
28735                 }
28736             }
28737             if (extendedConfigCache) {
28738                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28739             }
28740         }
28741         if (sourceFile) {
28742             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28743             if (extendedResult.extendedSourceFiles) {
28744                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28745             }
28746         }
28747         if (extendedResult.parseDiagnostics.length) {
28748             errors.push.apply(errors, extendedResult.parseDiagnostics);
28749             return undefined;
28750         }
28751         return extendedConfig;
28752     }
28753     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28754         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28755             return false;
28756         }
28757         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28758         return typeof result === "boolean" && result;
28759     }
28760     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28761         var errors = [];
28762         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28763         return { options: options, errors: errors };
28764     }
28765     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28766     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28767         var errors = [];
28768         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28769         return { options: options, errors: errors };
28770     }
28771     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28772     function getDefaultCompilerOptions(configFileName) {
28773         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28774             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28775             : {};
28776         return options;
28777     }
28778     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28779         var options = getDefaultCompilerOptions(configFileName);
28780         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28781         if (configFileName) {
28782             options.configFilePath = ts.normalizeSlashes(configFileName);
28783         }
28784         return options;
28785     }
28786     function getDefaultTypeAcquisition(configFileName) {
28787         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28788     }
28789     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28790         var options = getDefaultTypeAcquisition(configFileName);
28791         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28792         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28793         return options;
28794     }
28795     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28796         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28797     }
28798     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28799         if (!jsonOptions) {
28800             return;
28801         }
28802         for (var id in jsonOptions) {
28803             var opt = optionsNameMap.get(id);
28804             if (opt) {
28805                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28806             }
28807             else {
28808                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28809             }
28810         }
28811         return defaultOptions;
28812     }
28813     function convertJsonOption(opt, value, basePath, errors) {
28814         if (isCompilerOptionsValue(opt, value)) {
28815             var optType = opt.type;
28816             if (optType === "list" && ts.isArray(value)) {
28817                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28818             }
28819             else if (!ts.isString(optType)) {
28820                 return convertJsonOptionOfCustomType(opt, value, errors);
28821             }
28822             return normalizeNonListOptionValue(opt, basePath, value);
28823         }
28824         else {
28825             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28826         }
28827     }
28828     function normalizeOptionValue(option, basePath, value) {
28829         if (isNullOrUndefined(value))
28830             return undefined;
28831         if (option.type === "list") {
28832             var listOption_1 = option;
28833             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28834                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28835             }
28836             return value;
28837         }
28838         else if (!ts.isString(option.type)) {
28839             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
28840         }
28841         return normalizeNonListOptionValue(option, basePath, value);
28842     }
28843     function normalizeNonListOptionValue(option, basePath, value) {
28844         if (option.isFilePath) {
28845             value = ts.getNormalizedAbsolutePath(value, basePath);
28846             if (value === "") {
28847                 value = ".";
28848             }
28849         }
28850         return value;
28851     }
28852     function convertJsonOptionOfCustomType(opt, value, errors) {
28853         if (isNullOrUndefined(value))
28854             return undefined;
28855         var key = value.toLowerCase();
28856         var val = opt.type.get(key);
28857         if (val !== undefined) {
28858             return val;
28859         }
28860         else {
28861             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
28862         }
28863     }
28864     function convertJsonOptionOfListType(option, values, basePath, errors) {
28865         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
28866     }
28867     function trimString(s) {
28868         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
28869     }
28870     /**
28871      * Tests for a path that ends in a recursive directory wildcard.
28872      * Matches **, \**, **\, and \**\, but not a**b.
28873      *
28874      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28875      *
28876      * Breakdown:
28877      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28878      *  \*\*        # matches the recursive directory wildcard "**".
28879      *  \/?$        # matches an optional trailing directory separator at the end of the string.
28880      */
28881     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
28882     /**
28883      * Tests for a path where .. appears after a recursive directory wildcard.
28884      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
28885      *
28886      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28887      *
28888      * Breakdown:
28889      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28890      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
28891      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
28892      *  \.\.        # matches a parent directory path component ".."
28893      *  ($|\/)      # matches either the end of the string or a directory separator.
28894      */
28895     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
28896     /**
28897      * Tests for a path containing a wildcard character in a directory component of the path.
28898      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
28899      *
28900      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28901      *
28902      * Breakdown:
28903      *  \/          # matches a directory separator.
28904      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
28905      *  [*?]        # matches either a wildcard character (* or ?)
28906      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
28907      *  \/          # matches a directory separator.
28908      */
28909     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
28910     /**
28911      * Matches the portion of a wildcard path that does not contain wildcards.
28912      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
28913      *
28914      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28915      *
28916      * Breakdown:
28917      *  ^                   # matches the beginning of the string
28918      *  [^*?]*              # matches any number of non-wildcard characters
28919      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
28920      *                      # a path component that contains at least one wildcard character (* or ?).
28921      */
28922     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
28923     /**
28924      * Expands an array of file specifications.
28925      *
28926      * @param filesSpecs The literal file names to include.
28927      * @param includeSpecs The wildcard file specifications to include.
28928      * @param excludeSpecs The wildcard file specifications to exclude.
28929      * @param basePath The base path for any relative file specifications.
28930      * @param options Compiler options.
28931      * @param host The host used to resolve files and directories.
28932      * @param errors An array for diagnostic reporting.
28933      */
28934     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
28935         basePath = ts.normalizePath(basePath);
28936         var validatedIncludeSpecs, validatedExcludeSpecs;
28937         // The exclude spec list is converted into a regular expression, which allows us to quickly
28938         // test whether a file or directory should be excluded before recursively traversing the
28939         // file system.
28940         if (includeSpecs) {
28941             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
28942         }
28943         if (excludeSpecs) {
28944             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
28945         }
28946         // Wildcard directories (provided as part of a wildcard path) are stored in a
28947         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
28948         // or a recursive directory. This information is used by filesystem watchers to monitor for
28949         // new entries in these paths.
28950         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
28951         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
28952         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
28953     }
28954     /**
28955      * Gets the file names from the provided config file specs that contain, files, include, exclude and
28956      * other properties needed to resolve the file names
28957      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
28958      * @param basePath The base path for any relative file specifications.
28959      * @param options Compiler options.
28960      * @param host The host used to resolve files and directories.
28961      * @param extraFileExtensions optionaly file extra file extension information from host
28962      */
28963     /* @internal */
28964     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
28965         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28966         basePath = ts.normalizePath(basePath);
28967         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28968         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
28969         // file map with a possibly case insensitive key. We use this map later when when including
28970         // wildcard paths.
28971         var literalFileMap = ts.createMap();
28972         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
28973         // file map with a possibly case insensitive key. We use this map to store paths matched
28974         // via wildcard, and to handle extension priority.
28975         var wildcardFileMap = ts.createMap();
28976         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
28977         // file map with a possibly case insensitive key. We use this map to store paths matched
28978         // via wildcard of *.json kind
28979         var wildCardJsonFileMap = ts.createMap();
28980         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
28981         // Rather than requery this for each file and filespec, we query the supported extensions
28982         // once and store it on the expansion context.
28983         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
28984         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
28985         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
28986         // remove a literal file.
28987         if (filesSpecs) {
28988             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
28989                 var fileName = filesSpecs_1[_i];
28990                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
28991                 literalFileMap.set(keyMapper(file), file);
28992             }
28993         }
28994         var jsonOnlyIncludeRegexes;
28995         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
28996             var _loop_5 = function (file) {
28997                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
28998                     // Valid only if *.json specified
28999                     if (!jsonOnlyIncludeRegexes) {
29000                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29001                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29002                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29003                     }
29004                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29005                     if (includeIndex !== -1) {
29006                         var key_1 = keyMapper(file);
29007                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29008                             wildCardJsonFileMap.set(key_1, file);
29009                         }
29010                     }
29011                     return "continue";
29012                 }
29013                 // If we have already included a literal or wildcard path with a
29014                 // higher priority extension, we should skip this file.
29015                 //
29016                 // This handles cases where we may encounter both <file>.ts and
29017                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29018                 // directory when they are compilation outputs.
29019                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29020                     return "continue";
29021                 }
29022                 // We may have included a wildcard path with a lower priority
29023                 // extension due to the user-defined order of entries in the
29024                 // "include" array. If there is a lower priority extension in the
29025                 // same directory, we should remove it.
29026                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29027                 var key = keyMapper(file);
29028                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29029                     wildcardFileMap.set(key, file);
29030                 }
29031             };
29032             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29033                 var file = _b[_a];
29034                 _loop_5(file);
29035             }
29036         }
29037         var literalFiles = ts.arrayFrom(literalFileMap.values());
29038         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29039         return {
29040             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29041             wildcardDirectories: wildcardDirectories,
29042             spec: spec
29043         };
29044     }
29045     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29046     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29047         return specs.filter(function (spec) {
29048             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29049             if (diag !== undefined) {
29050                 errors.push(createDiagnostic(diag, spec));
29051             }
29052             return diag === undefined;
29053         });
29054         function createDiagnostic(message, spec) {
29055             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29056             return element ?
29057                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29058                 ts.createCompilerDiagnostic(message, spec);
29059         }
29060     }
29061     function specToDiagnostic(spec, allowTrailingRecursion) {
29062         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29063             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29064         }
29065         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29066             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29067         }
29068     }
29069     /**
29070      * Gets directories in a set of include patterns that should be watched for changes.
29071      */
29072     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29073         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29074         // of the pattern:
29075         //
29076         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29077         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29078         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29079         //
29080         // We watch a directory without recursion if it contains a wildcard in the file segment of
29081         // the pattern:
29082         //
29083         //  /a/b/*      - Watch /a/b directly to catch any new file
29084         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29085         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29086         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29087         var wildcardDirectories = {};
29088         if (include !== undefined) {
29089             var recursiveKeys = [];
29090             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29091                 var file = include_1[_i];
29092                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29093                 if (excludeRegex && excludeRegex.test(spec)) {
29094                     continue;
29095                 }
29096                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29097                 if (match) {
29098                     var key = match.key, flags = match.flags;
29099                     var existingFlags = wildcardDirectories[key];
29100                     if (existingFlags === undefined || existingFlags < flags) {
29101                         wildcardDirectories[key] = flags;
29102                         if (flags === 1 /* Recursive */) {
29103                             recursiveKeys.push(key);
29104                         }
29105                     }
29106                 }
29107             }
29108             // Remove any subpaths under an existing recursively watched directory.
29109             for (var key in wildcardDirectories) {
29110                 if (ts.hasProperty(wildcardDirectories, key)) {
29111                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29112                         var recursiveKey = recursiveKeys_1[_a];
29113                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29114                             delete wildcardDirectories[key];
29115                         }
29116                     }
29117                 }
29118             }
29119         }
29120         return wildcardDirectories;
29121     }
29122     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29123         var match = wildcardDirectoryPattern.exec(spec);
29124         if (match) {
29125             return {
29126                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29127                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29128             };
29129         }
29130         if (ts.isImplicitGlob(spec)) {
29131             return { key: spec, flags: 1 /* Recursive */ };
29132         }
29133         return undefined;
29134     }
29135     /**
29136      * Determines whether a literal or wildcard file has already been included that has a higher
29137      * extension priority.
29138      *
29139      * @param file The path to the file.
29140      * @param extensionPriority The priority of the extension.
29141      * @param context The expansion context.
29142      */
29143     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29144         var extensionPriority = ts.getExtensionPriority(file, extensions);
29145         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29146         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29147             var higherPriorityExtension = extensions[i];
29148             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29149             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29150                 return true;
29151             }
29152         }
29153         return false;
29154     }
29155     /**
29156      * Removes files included via wildcard expansion with a lower extension priority that have
29157      * already been included.
29158      *
29159      * @param file The path to the file.
29160      * @param extensionPriority The priority of the extension.
29161      * @param context The expansion context.
29162      */
29163     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29164         var extensionPriority = ts.getExtensionPriority(file, extensions);
29165         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29166         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29167             var lowerPriorityExtension = extensions[i];
29168             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29169             wildcardFiles.delete(lowerPriorityPath);
29170         }
29171     }
29172     /**
29173      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29174      * Also converts enum values back to strings.
29175      */
29176     /* @internal */
29177     function convertCompilerOptionsForTelemetry(opts) {
29178         var out = {};
29179         for (var key in opts) {
29180             if (opts.hasOwnProperty(key)) {
29181                 var type = getOptionFromName(key);
29182                 if (type !== undefined) { // Ignore unknown options
29183                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29184                 }
29185             }
29186         }
29187         return out;
29188     }
29189     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29190     function getOptionValueWithEmptyStrings(value, option) {
29191         switch (option.type) {
29192             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29193                 return "";
29194             case "string": // Could be any arbitrary string -- use empty string instead.
29195                 return "";
29196             case "number": // Allow numbers, but be sure to check it's actually a number.
29197                 return typeof value === "number" ? value : "";
29198             case "boolean":
29199                 return typeof value === "boolean" ? value : "";
29200             case "list":
29201                 var elementType_1 = option.element;
29202                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29203             default:
29204                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29205                     if (optionEnumValue === value) {
29206                         return optionStringValue;
29207                     }
29208                 }); // TODO: GH#18217
29209         }
29210     }
29211 })(ts || (ts = {}));
29212 var ts;
29213 (function (ts) {
29214     function trace(host) {
29215         host.trace(ts.formatMessage.apply(undefined, arguments));
29216     }
29217     ts.trace = trace;
29218     /* @internal */
29219     function isTraceEnabled(compilerOptions, host) {
29220         return !!compilerOptions.traceResolution && host.trace !== undefined;
29221     }
29222     ts.isTraceEnabled = isTraceEnabled;
29223     function withPackageId(packageInfo, r) {
29224         var packageId;
29225         if (r && packageInfo) {
29226             var packageJsonContent = packageInfo.packageJsonContent;
29227             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29228                 packageId = {
29229                     name: packageJsonContent.name,
29230                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29231                     version: packageJsonContent.version
29232                 };
29233             }
29234         }
29235         return r && { path: r.path, extension: r.ext, packageId: packageId };
29236     }
29237     function noPackageId(r) {
29238         return withPackageId(/*packageInfo*/ undefined, r);
29239     }
29240     function removeIgnoredPackageId(r) {
29241         if (r) {
29242             ts.Debug.assert(r.packageId === undefined);
29243             return { path: r.path, ext: r.extension };
29244         }
29245     }
29246     /**
29247      * Kinds of file that we are currently looking for.
29248      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29249      */
29250     var Extensions;
29251     (function (Extensions) {
29252         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29253         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29254         Extensions[Extensions["Json"] = 2] = "Json";
29255         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29256         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29257     })(Extensions || (Extensions = {}));
29258     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29259     function resolvedTypeScriptOnly(resolved) {
29260         if (!resolved) {
29261             return undefined;
29262         }
29263         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29264         return { fileName: resolved.path, packageId: resolved.packageId };
29265     }
29266     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29267         var _a;
29268         if (resultFromCache) {
29269             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29270             return resultFromCache;
29271         }
29272         return {
29273             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29274             failedLookupLocations: failedLookupLocations
29275         };
29276     }
29277     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29278         if (!ts.hasProperty(jsonContent, fieldName)) {
29279             if (state.traceEnabled) {
29280                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29281             }
29282             return;
29283         }
29284         var value = jsonContent[fieldName];
29285         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29286             if (state.traceEnabled) {
29287                 // eslint-disable-next-line no-null/no-null
29288                 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);
29289             }
29290             return;
29291         }
29292         return value;
29293     }
29294     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29295         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29296         if (fileName === undefined) {
29297             return;
29298         }
29299         if (!fileName) {
29300             if (state.traceEnabled) {
29301                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29302             }
29303             return;
29304         }
29305         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29306         if (state.traceEnabled) {
29307             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29308         }
29309         return path;
29310     }
29311     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29312         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29313             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29314     }
29315     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29316         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29317     }
29318     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29319         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29320     }
29321     function readPackageJsonTypesVersionsField(jsonContent, state) {
29322         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29323         if (typesVersions === undefined)
29324             return;
29325         if (state.traceEnabled) {
29326             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29327         }
29328         return typesVersions;
29329     }
29330     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29331         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29332         if (typesVersions === undefined)
29333             return;
29334         if (state.traceEnabled) {
29335             for (var key in typesVersions) {
29336                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29337                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29338                 }
29339             }
29340         }
29341         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29342         if (!result) {
29343             if (state.traceEnabled) {
29344                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29345             }
29346             return;
29347         }
29348         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29349         if (typeof bestVersionPaths !== "object") {
29350             if (state.traceEnabled) {
29351                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29352             }
29353             return;
29354         }
29355         return result;
29356     }
29357     var typeScriptVersion;
29358     /* @internal */
29359     function getPackageJsonTypesVersionsPaths(typesVersions) {
29360         if (!typeScriptVersion)
29361             typeScriptVersion = new ts.Version(ts.version);
29362         for (var key in typesVersions) {
29363             if (!ts.hasProperty(typesVersions, key))
29364                 continue;
29365             var keyRange = ts.VersionRange.tryParse(key);
29366             if (keyRange === undefined) {
29367                 continue;
29368             }
29369             // return the first entry whose range matches the current compiler version.
29370             if (keyRange.test(typeScriptVersion)) {
29371                 return { version: key, paths: typesVersions[key] };
29372             }
29373         }
29374     }
29375     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29376     function getEffectiveTypeRoots(options, host) {
29377         if (options.typeRoots) {
29378             return options.typeRoots;
29379         }
29380         var currentDirectory;
29381         if (options.configFilePath) {
29382             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29383         }
29384         else if (host.getCurrentDirectory) {
29385             currentDirectory = host.getCurrentDirectory();
29386         }
29387         if (currentDirectory !== undefined) {
29388             return getDefaultTypeRoots(currentDirectory, host);
29389         }
29390     }
29391     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29392     /**
29393      * Returns the path to every node_modules/@types directory from some ancestor directory.
29394      * Returns undefined if there are none.
29395      */
29396     function getDefaultTypeRoots(currentDirectory, host) {
29397         if (!host.directoryExists) {
29398             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29399             // And if it doesn't exist, tough.
29400         }
29401         var typeRoots;
29402         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29403             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29404             if (host.directoryExists(atTypes)) {
29405                 (typeRoots || (typeRoots = [])).push(atTypes);
29406             }
29407             return undefined;
29408         });
29409         return typeRoots;
29410     }
29411     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29412     /**
29413      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29414      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29415      * is assumed to be the same as root directory of the project.
29416      */
29417     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29418         var traceEnabled = isTraceEnabled(options, host);
29419         if (redirectedReference) {
29420             options = redirectedReference.commandLine.options;
29421         }
29422         var failedLookupLocations = [];
29423         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29424         var typeRoots = getEffectiveTypeRoots(options, host);
29425         if (traceEnabled) {
29426             if (containingFile === undefined) {
29427                 if (typeRoots === undefined) {
29428                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29429                 }
29430                 else {
29431                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29432                 }
29433             }
29434             else {
29435                 if (typeRoots === undefined) {
29436                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29437                 }
29438                 else {
29439                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29440                 }
29441             }
29442             if (redirectedReference) {
29443                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29444             }
29445         }
29446         var resolved = primaryLookup();
29447         var primary = true;
29448         if (!resolved) {
29449             resolved = secondaryLookup();
29450             primary = false;
29451         }
29452         var resolvedTypeReferenceDirective;
29453         if (resolved) {
29454             var fileName = resolved.fileName, packageId = resolved.packageId;
29455             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29456             if (traceEnabled) {
29457                 if (packageId) {
29458                     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);
29459                 }
29460                 else {
29461                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29462                 }
29463             }
29464             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29465         }
29466         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29467         function primaryLookup() {
29468             // Check primary library paths
29469             if (typeRoots && typeRoots.length) {
29470                 if (traceEnabled) {
29471                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29472                 }
29473                 return ts.firstDefined(typeRoots, function (typeRoot) {
29474                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29475                     var candidateDirectory = ts.getDirectoryPath(candidate);
29476                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29477                     if (!directoryExists && traceEnabled) {
29478                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29479                     }
29480                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29481                 });
29482             }
29483             else {
29484                 if (traceEnabled) {
29485                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29486                 }
29487             }
29488         }
29489         function secondaryLookup() {
29490             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29491             if (initialLocationForSecondaryLookup !== undefined) {
29492                 // check secondary locations
29493                 if (traceEnabled) {
29494                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29495                 }
29496                 var result = void 0;
29497                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29498                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29499                     result = searchResult && searchResult.value;
29500                 }
29501                 else {
29502                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29503                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29504                 }
29505                 var resolvedFile = resolvedTypeScriptOnly(result);
29506                 if (!resolvedFile && traceEnabled) {
29507                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29508                 }
29509                 return resolvedFile;
29510             }
29511             else {
29512                 if (traceEnabled) {
29513                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29514                 }
29515             }
29516         }
29517     }
29518     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29519     /**
29520      * Given a set of options, returns the set of type directive names
29521      *   that should be included for this program automatically.
29522      * This list could either come from the config file,
29523      *   or from enumerating the types root + initial secondary types lookup location.
29524      * More type directives might appear in the program later as a result of loading actual source files;
29525      *   this list is only the set of defaults that are implicitly included.
29526      */
29527     function getAutomaticTypeDirectiveNames(options, host) {
29528         // Use explicit type list from tsconfig.json
29529         if (options.types) {
29530             return options.types;
29531         }
29532         // Walk the primary type lookup locations
29533         var result = [];
29534         if (host.directoryExists && host.getDirectories) {
29535             var typeRoots = getEffectiveTypeRoots(options, host);
29536             if (typeRoots) {
29537                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29538                     var root = typeRoots_1[_i];
29539                     if (host.directoryExists(root)) {
29540                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29541                             var typeDirectivePath = _b[_a];
29542                             var normalized = ts.normalizePath(typeDirectivePath);
29543                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29544                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29545                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29546                             // eslint-disable-next-line no-null/no-null
29547                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29548                             if (!isNotNeededPackage) {
29549                                 var baseFileName = ts.getBaseFileName(normalized);
29550                                 // At this stage, skip results with leading dot.
29551                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29552                                     // Return just the type directive names
29553                                     result.push(baseFileName);
29554                                 }
29555                             }
29556                         }
29557                     }
29558                 }
29559             }
29560         }
29561         return result;
29562     }
29563     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29564     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29565         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29566     }
29567     ts.createModuleResolutionCache = createModuleResolutionCache;
29568     /*@internal*/
29569     function createCacheWithRedirects(options) {
29570         var ownMap = ts.createMap();
29571         var redirectsMap = ts.createMap();
29572         return {
29573             ownMap: ownMap,
29574             redirectsMap: redirectsMap,
29575             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29576             clear: clear,
29577             setOwnOptions: setOwnOptions,
29578             setOwnMap: setOwnMap
29579         };
29580         function setOwnOptions(newOptions) {
29581             options = newOptions;
29582         }
29583         function setOwnMap(newOwnMap) {
29584             ownMap = newOwnMap;
29585         }
29586         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29587             if (!redirectedReference) {
29588                 return ownMap;
29589             }
29590             var path = redirectedReference.sourceFile.path;
29591             var redirects = redirectsMap.get(path);
29592             if (!redirects) {
29593                 // Reuse map if redirected reference map uses same resolution
29594                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29595                 redirectsMap.set(path, redirects);
29596             }
29597             return redirects;
29598         }
29599         function clear() {
29600             ownMap.clear();
29601             redirectsMap.clear();
29602         }
29603     }
29604     ts.createCacheWithRedirects = createCacheWithRedirects;
29605     /*@internal*/
29606     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29607         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29608         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29609             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29610             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29611         }
29612         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29613             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29614             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29615         }
29616         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29617             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29618             var result = cache.get(key);
29619             if (!result) {
29620                 result = create();
29621                 cache.set(key, result);
29622             }
29623             return result;
29624         }
29625         function createPerModuleNameCache() {
29626             var directoryPathMap = ts.createMap();
29627             return { get: get, set: set };
29628             function get(directory) {
29629                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29630             }
29631             /**
29632              * At first this function add entry directory -> module resolution result to the table.
29633              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29634              * and for every parent folder in set it adds entry: parent -> module resolution. .
29635              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29636              * Set of parent folders that should have the same result will be:
29637              * [
29638              *     /a/b/c/d, /a/b/c, /a/b
29639              * ]
29640              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29641              */
29642             function set(directory, result) {
29643                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29644                 // if entry is already in cache do nothing
29645                 if (directoryPathMap.has(path)) {
29646                     return;
29647                 }
29648                 directoryPathMap.set(path, result);
29649                 var resolvedFileName = result.resolvedModule &&
29650                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29651                 // find common prefix between directory and resolved file name
29652                 // this common prefix should be the shortest path that has the same resolution
29653                 // directory: /a/b/c/d/e
29654                 // resolvedFileName: /a/b/foo.d.ts
29655                 // commonPrefix: /a/b
29656                 // for failed lookups cache the result for every directory up to root
29657                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29658                 var current = path;
29659                 while (current !== commonPrefix) {
29660                     var parent = ts.getDirectoryPath(current);
29661                     if (parent === current || directoryPathMap.has(parent)) {
29662                         break;
29663                     }
29664                     directoryPathMap.set(parent, result);
29665                     current = parent;
29666                 }
29667             }
29668             function getCommonPrefix(directory, resolution) {
29669                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29670                 // find first position where directory and resolution differs
29671                 var i = 0;
29672                 var limit = Math.min(directory.length, resolutionDirectory.length);
29673                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29674                     i++;
29675                 }
29676                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29677                     return directory;
29678                 }
29679                 var rootLength = ts.getRootLength(directory);
29680                 if (i < rootLength) {
29681                     return undefined;
29682                 }
29683                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29684                 if (sep === -1) {
29685                     return undefined;
29686                 }
29687                 return directory.substr(0, Math.max(sep, rootLength));
29688             }
29689         }
29690     }
29691     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29692     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29693         var containingDirectory = ts.getDirectoryPath(containingFile);
29694         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29695         return perFolderCache && perFolderCache.get(moduleName);
29696     }
29697     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29698     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29699         var traceEnabled = isTraceEnabled(compilerOptions, host);
29700         if (redirectedReference) {
29701             compilerOptions = redirectedReference.commandLine.options;
29702         }
29703         if (traceEnabled) {
29704             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29705             if (redirectedReference) {
29706                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29707             }
29708         }
29709         var containingDirectory = ts.getDirectoryPath(containingFile);
29710         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29711         var result = perFolderCache && perFolderCache.get(moduleName);
29712         if (result) {
29713             if (traceEnabled) {
29714                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29715             }
29716         }
29717         else {
29718             var moduleResolution = compilerOptions.moduleResolution;
29719             if (moduleResolution === undefined) {
29720                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29721                 if (traceEnabled) {
29722                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29723                 }
29724             }
29725             else {
29726                 if (traceEnabled) {
29727                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29728                 }
29729             }
29730             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29731             switch (moduleResolution) {
29732                 case ts.ModuleResolutionKind.NodeJs:
29733                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29734                     break;
29735                 case ts.ModuleResolutionKind.Classic:
29736                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29737                     break;
29738                 default:
29739                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29740             }
29741             if (result && result.resolvedModule)
29742                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29743             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29744             if (perFolderCache) {
29745                 perFolderCache.set(moduleName, result);
29746                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29747                     // put result in per-module name cache
29748                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29749                 }
29750             }
29751         }
29752         if (traceEnabled) {
29753             if (result.resolvedModule) {
29754                 if (result.resolvedModule.packageId) {
29755                     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));
29756                 }
29757                 else {
29758                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29759                 }
29760             }
29761             else {
29762                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29763             }
29764         }
29765         return result;
29766     }
29767     ts.resolveModuleName = resolveModuleName;
29768     /**
29769      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29770      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29771      * can be resolved successfully by TypeScript compiler and runtime module loader.
29772      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29773      * fallback to standard resolution routine.
29774      *
29775      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29776      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29777      * be '/a/b/c/d'
29778      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29779      * will be resolved based on the content of the module name.
29780      * Structure of 'paths' compiler options
29781      * 'paths': {
29782      *    pattern-1: [...substitutions],
29783      *    pattern-2: [...substitutions],
29784      *    ...
29785      *    pattern-n: [...substitutions]
29786      * }
29787      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29788      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29789      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29790      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29791      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29792      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29793      * from the candidate location.
29794      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29795      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29796      * will be converted to absolute using baseUrl.
29797      * For example:
29798      * baseUrl: /a/b/c
29799      * "paths": {
29800      *     // match all module names
29801      *     "*": [
29802      *         "*",        // use matched name as is,
29803      *                     // <matched name> will be looked as /a/b/c/<matched name>
29804      *
29805      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29806      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29807      *     ],
29808      *     // match module names that start with 'components/'
29809      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29810      *                                              // it is rooted so it will be final candidate location
29811      * }
29812      *
29813      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29814      * they were in the same location. For example lets say there are two files
29815      * '/local/src/content/file1.ts'
29816      * '/shared/components/contracts/src/content/protocols/file2.ts'
29817      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29818      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29819      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29820      * root dirs were merged together.
29821      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29822      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29823      * '/local/src/content/protocols/file2' and try to load it - failure.
29824      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29825      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29826      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29827      */
29828     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29829         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29830         if (resolved)
29831             return resolved.value;
29832         if (!ts.isExternalModuleNameRelative(moduleName)) {
29833             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29834         }
29835         else {
29836             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29837         }
29838     }
29839     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
29840         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
29841         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
29842             if (state.traceEnabled) {
29843                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29844                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
29845             }
29846             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
29847         }
29848     }
29849     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
29850         if (!state.compilerOptions.rootDirs) {
29851             return undefined;
29852         }
29853         if (state.traceEnabled) {
29854             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
29855         }
29856         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
29857         var matchedRootDir;
29858         var matchedNormalizedPrefix;
29859         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
29860             var rootDir = _a[_i];
29861             // rootDirs are expected to be absolute
29862             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
29863             // using location of tsconfig.json as base location
29864             var normalizedRoot = ts.normalizePath(rootDir);
29865             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
29866                 normalizedRoot += ts.directorySeparator;
29867             }
29868             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
29869                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
29870             if (state.traceEnabled) {
29871                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
29872             }
29873             if (isLongestMatchingPrefix) {
29874                 matchedNormalizedPrefix = normalizedRoot;
29875                 matchedRootDir = rootDir;
29876             }
29877         }
29878         if (matchedNormalizedPrefix) {
29879             if (state.traceEnabled) {
29880                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
29881             }
29882             var suffix = candidate.substr(matchedNormalizedPrefix.length);
29883             // first - try to load from a initial location
29884             if (state.traceEnabled) {
29885                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
29886             }
29887             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
29888             if (resolvedFileName) {
29889                 return resolvedFileName;
29890             }
29891             if (state.traceEnabled) {
29892                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
29893             }
29894             // then try to resolve using remaining entries in rootDirs
29895             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
29896                 var rootDir = _c[_b];
29897                 if (rootDir === matchedRootDir) {
29898                     // skip the initially matched entry
29899                     continue;
29900                 }
29901                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
29902                 if (state.traceEnabled) {
29903                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
29904                 }
29905                 var baseDirectory = ts.getDirectoryPath(candidate_1);
29906                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
29907                 if (resolvedFileName_1) {
29908                     return resolvedFileName_1;
29909                 }
29910             }
29911             if (state.traceEnabled) {
29912                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
29913             }
29914         }
29915         return undefined;
29916     }
29917     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
29918         var baseUrl = state.compilerOptions.baseUrl;
29919         if (!baseUrl) {
29920             return undefined;
29921         }
29922         if (state.traceEnabled) {
29923             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29924         }
29925         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
29926         if (state.traceEnabled) {
29927             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
29928         }
29929         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
29930     }
29931     /**
29932      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
29933      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
29934      * Throws an error if the module can't be resolved.
29935      */
29936     /* @internal */
29937     function resolveJSModule(moduleName, initialDir, host) {
29938         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
29939         if (!resolvedModule) {
29940             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
29941         }
29942         return resolvedModule.resolvedFileName;
29943     }
29944     ts.resolveJSModule = resolveJSModule;
29945     /* @internal */
29946     function tryResolveJSModule(moduleName, initialDir, host) {
29947         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
29948         return resolvedModule && resolvedModule.resolvedFileName;
29949     }
29950     ts.tryResolveJSModule = tryResolveJSModule;
29951     var jsOnlyExtensions = [Extensions.JavaScript];
29952     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
29953     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
29954     var tsconfigExtensions = [Extensions.TSConfig];
29955     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
29956         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
29957     }
29958     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
29959         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
29960     }
29961     ts.nodeModuleNameResolver = nodeModuleNameResolver;
29962     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
29963         var _a, _b;
29964         var traceEnabled = isTraceEnabled(compilerOptions, host);
29965         var failedLookupLocations = [];
29966         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29967         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
29968         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);
29969         function tryResolve(extensions) {
29970             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
29971             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
29972             if (resolved) {
29973                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
29974             }
29975             if (!ts.isExternalModuleNameRelative(moduleName)) {
29976                 if (traceEnabled) {
29977                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
29978                 }
29979                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
29980                 if (!resolved_1)
29981                     return undefined;
29982                 var resolvedValue = resolved_1.value;
29983                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
29984                     var path = realPath(resolvedValue.path, host, traceEnabled);
29985                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
29986                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
29987                 }
29988                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
29989                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
29990             }
29991             else {
29992                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
29993                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
29994                 // Treat explicit "node_modules" import as an external library import.
29995                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
29996             }
29997         }
29998     }
29999     function realPath(path, host, traceEnabled) {
30000         if (!host.realpath) {
30001             return path;
30002         }
30003         var real = ts.normalizePath(host.realpath(path));
30004         if (traceEnabled) {
30005             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30006         }
30007         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30008         return real;
30009     }
30010     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30011         if (state.traceEnabled) {
30012             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30013         }
30014         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30015             if (!onlyRecordFailures) {
30016                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30017                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30018                     if (state.traceEnabled) {
30019                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30020                     }
30021                     onlyRecordFailures = true;
30022                 }
30023             }
30024             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30025             if (resolvedFromFile) {
30026                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30027                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30028                 return withPackageId(packageInfo, resolvedFromFile);
30029             }
30030         }
30031         if (!onlyRecordFailures) {
30032             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30033             if (!candidateExists) {
30034                 if (state.traceEnabled) {
30035                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30036                 }
30037                 onlyRecordFailures = true;
30038             }
30039         }
30040         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30041     }
30042     /*@internal*/
30043     ts.nodeModulesPathPart = "/node_modules/";
30044     /*@internal*/
30045     function pathContainsNodeModules(path) {
30046         return ts.stringContains(path, ts.nodeModulesPathPart);
30047     }
30048     ts.pathContainsNodeModules = pathContainsNodeModules;
30049     /**
30050      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30051      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30052      *
30053      * packageDirectory is the directory of the package itself.
30054      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30055      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30056      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30057      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30058      */
30059     function parseNodeModuleFromPath(resolved) {
30060         var path = ts.normalizePath(resolved.path);
30061         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30062         if (idx === -1) {
30063             return undefined;
30064         }
30065         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30066         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30067         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30068             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30069         }
30070         return path.slice(0, indexAfterPackageName);
30071     }
30072     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30073         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30074         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30075     }
30076     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30077         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30078     }
30079     /**
30080      * @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
30081      * 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.
30082      */
30083     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30084         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30085             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30086             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30087         }
30088         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30089         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30090         if (resolvedByAddingExtension) {
30091             return resolvedByAddingExtension;
30092         }
30093         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30094         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30095         if (ts.hasJSFileExtension(candidate)) {
30096             var extensionless = ts.removeFileExtension(candidate);
30097             if (state.traceEnabled) {
30098                 var extension = candidate.substring(extensionless.length);
30099                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30100             }
30101             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30102         }
30103     }
30104     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30105     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30106         if (!onlyRecordFailures) {
30107             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30108             var directory = ts.getDirectoryPath(candidate);
30109             if (directory) {
30110                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30111             }
30112         }
30113         switch (extensions) {
30114             case Extensions.DtsOnly:
30115                 return tryExtension(".d.ts" /* Dts */);
30116             case Extensions.TypeScript:
30117                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30118             case Extensions.JavaScript:
30119                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30120             case Extensions.TSConfig:
30121             case Extensions.Json:
30122                 return tryExtension(".json" /* Json */);
30123         }
30124         function tryExtension(ext) {
30125             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30126             return path === undefined ? undefined : { path: path, ext: ext };
30127         }
30128     }
30129     /** Return the file if it exists. */
30130     function tryFile(fileName, onlyRecordFailures, state) {
30131         if (!onlyRecordFailures) {
30132             if (state.host.fileExists(fileName)) {
30133                 if (state.traceEnabled) {
30134                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30135                 }
30136                 return fileName;
30137             }
30138             else {
30139                 if (state.traceEnabled) {
30140                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30141                 }
30142             }
30143         }
30144         state.failedLookupLocations.push(fileName);
30145         return undefined;
30146     }
30147     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30148         if (considerPackageJson === void 0) { considerPackageJson = true; }
30149         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30150         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30151         var versionPaths = packageInfo && packageInfo.versionPaths;
30152         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30153     }
30154     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30155         var host = state.host, traceEnabled = state.traceEnabled;
30156         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30157         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30158         if (directoryExists && host.fileExists(packageJsonPath)) {
30159             var packageJsonContent = ts.readJson(packageJsonPath, host);
30160             if (traceEnabled) {
30161                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30162             }
30163             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30164             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30165         }
30166         else {
30167             if (directoryExists && traceEnabled) {
30168                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30169             }
30170             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30171             state.failedLookupLocations.push(packageJsonPath);
30172         }
30173     }
30174     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30175         var packageFile;
30176         if (jsonContent) {
30177             switch (extensions) {
30178                 case Extensions.JavaScript:
30179                 case Extensions.Json:
30180                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30181                     break;
30182                 case Extensions.TypeScript:
30183                     // When resolving typescript modules, try resolving using main field as well
30184                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30185                     break;
30186                 case Extensions.DtsOnly:
30187                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30188                     break;
30189                 case Extensions.TSConfig:
30190                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30191                     break;
30192                 default:
30193                     return ts.Debug.assertNever(extensions);
30194             }
30195         }
30196         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30197             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30198             if (fromFile) {
30199                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30200                 if (resolved) {
30201                     return noPackageId(resolved);
30202                 }
30203                 if (state.traceEnabled) {
30204                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30205                 }
30206             }
30207             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30208             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30209             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30210             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30211         };
30212         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30213         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30214         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30215         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30216             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30217             if (state.traceEnabled) {
30218                 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);
30219             }
30220             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30221             if (result) {
30222                 return removeIgnoredPackageId(result.value);
30223             }
30224         }
30225         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30226         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30227         if (packageFileResult)
30228             return packageFileResult;
30229         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30230     }
30231     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30232     function resolvedIfExtensionMatches(extensions, path) {
30233         var ext = ts.tryGetExtensionFromPath(path);
30234         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30235     }
30236     /** True if `extension` is one of the supported `extensions`. */
30237     function extensionIsOk(extensions, extension) {
30238         switch (extensions) {
30239             case Extensions.JavaScript:
30240                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30241             case Extensions.TSConfig:
30242             case Extensions.Json:
30243                 return extension === ".json" /* Json */;
30244             case Extensions.TypeScript:
30245                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30246             case Extensions.DtsOnly:
30247                 return extension === ".d.ts" /* Dts */;
30248         }
30249     }
30250     /* @internal */
30251     function parsePackageName(moduleName) {
30252         var idx = moduleName.indexOf(ts.directorySeparator);
30253         if (moduleName[0] === "@") {
30254             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30255         }
30256         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30257     }
30258     ts.parsePackageName = parsePackageName;
30259     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30260         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30261     }
30262     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30263         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30264         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30265     }
30266     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30267         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30268         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30269             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30270                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30271                 if (resolutionFromCache) {
30272                     return resolutionFromCache;
30273                 }
30274                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30275             }
30276         });
30277     }
30278     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30279         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30280         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30281         if (!nodeModulesFolderExists && state.traceEnabled) {
30282             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30283         }
30284         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30285         if (packageResult) {
30286             return packageResult;
30287         }
30288         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30289             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30290             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30291             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30292                 if (state.traceEnabled) {
30293                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30294                 }
30295                 nodeModulesAtTypesExists = false;
30296             }
30297             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30298         }
30299     }
30300     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30301         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30302         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30303         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30304         if (packageInfo) {
30305             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30306             if (fromFile) {
30307                 return noPackageId(fromFile);
30308             }
30309             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30310             return withPackageId(packageInfo, fromDirectory);
30311         }
30312         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30313             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30314                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30315             return withPackageId(packageInfo, pathAndExtension);
30316         };
30317         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30318         if (rest !== "") { // If "rest" is empty, we just did this search above.
30319             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30320             // 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.
30321             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30322             if (packageInfo && packageInfo.versionPaths) {
30323                 if (state.traceEnabled) {
30324                     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);
30325                 }
30326                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30327                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30328                 if (fromPaths) {
30329                     return fromPaths.value;
30330                 }
30331             }
30332         }
30333         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30334     }
30335     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30336         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30337         if (matchedPattern) {
30338             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30339             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30340             if (state.traceEnabled) {
30341                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30342             }
30343             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30344                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30345                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30346                 if (state.traceEnabled) {
30347                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30348                 }
30349                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30350                 var extension = ts.tryGetExtensionFromPath(candidate);
30351                 if (extension !== undefined) {
30352                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30353                     if (path_1 !== undefined) {
30354                         return noPackageId({ path: path_1, ext: extension });
30355                     }
30356                 }
30357                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30358             });
30359             return { value: resolved };
30360         }
30361     }
30362     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30363     var mangledScopedPackageSeparator = "__";
30364     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30365     function mangleScopedPackageNameWithTrace(packageName, state) {
30366         var mangled = mangleScopedPackageName(packageName);
30367         if (state.traceEnabled && mangled !== packageName) {
30368             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30369         }
30370         return mangled;
30371     }
30372     /* @internal */
30373     function getTypesPackageName(packageName) {
30374         return "@types/" + mangleScopedPackageName(packageName);
30375     }
30376     ts.getTypesPackageName = getTypesPackageName;
30377     /* @internal */
30378     function mangleScopedPackageName(packageName) {
30379         if (ts.startsWith(packageName, "@")) {
30380             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30381             if (replaceSlash !== packageName) {
30382                 return replaceSlash.slice(1); // Take off the "@"
30383             }
30384         }
30385         return packageName;
30386     }
30387     ts.mangleScopedPackageName = mangleScopedPackageName;
30388     /* @internal */
30389     function getPackageNameFromTypesPackageName(mangledName) {
30390         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30391         if (withoutAtTypePrefix !== mangledName) {
30392             return unmangleScopedPackageName(withoutAtTypePrefix);
30393         }
30394         return mangledName;
30395     }
30396     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30397     /* @internal */
30398     function unmangleScopedPackageName(typesPackageName) {
30399         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30400             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30401             typesPackageName;
30402     }
30403     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30404     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30405         var result = cache && cache.get(containingDirectory);
30406         if (result) {
30407             if (state.traceEnabled) {
30408                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30409             }
30410             state.resultFromCache = result;
30411             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30412         }
30413     }
30414     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30415         var traceEnabled = isTraceEnabled(compilerOptions, host);
30416         var failedLookupLocations = [];
30417         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30418         var containingDirectory = ts.getDirectoryPath(containingFile);
30419         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30420         // No originalPath because classic resolution doesn't resolve realPath
30421         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30422         function tryResolve(extensions) {
30423             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30424             if (resolvedUsingSettings) {
30425                 return { value: resolvedUsingSettings };
30426             }
30427             if (!ts.isExternalModuleNameRelative(moduleName)) {
30428                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30429                 // Climb up parent directories looking for a module.
30430                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30431                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30432                     if (resolutionFromCache) {
30433                         return resolutionFromCache;
30434                     }
30435                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30436                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30437                 });
30438                 if (resolved_3) {
30439                     return resolved_3;
30440                 }
30441                 if (extensions === Extensions.TypeScript) {
30442                     // If we didn't find the file normally, look it up in @types.
30443                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30444                 }
30445             }
30446             else {
30447                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30448                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30449             }
30450         }
30451     }
30452     ts.classicNameResolver = classicNameResolver;
30453     /**
30454      * A host may load a module from a global cache of typings.
30455      * This is the minumum code needed to expose that functionality; the rest is in the host.
30456      */
30457     /* @internal */
30458     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30459         var traceEnabled = isTraceEnabled(compilerOptions, host);
30460         if (traceEnabled) {
30461             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);
30462         }
30463         var failedLookupLocations = [];
30464         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30465         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30466         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30467     }
30468     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30469     /**
30470      * Wraps value to SearchResult.
30471      * @returns undefined if value is undefined or { value } otherwise
30472      */
30473     function toSearchResult(value) {
30474         return value !== undefined ? { value: value } : undefined;
30475     }
30476 })(ts || (ts = {}));
30477 /* @internal */
30478 var ts;
30479 (function (ts) {
30480     var ModuleInstanceState;
30481     (function (ModuleInstanceState) {
30482         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30483         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30484         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30485     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30486     function getModuleInstanceState(node, visited) {
30487         if (node.body && !node.body.parent) {
30488             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30489             setParentPointers(node, node.body);
30490         }
30491         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30492     }
30493     ts.getModuleInstanceState = getModuleInstanceState;
30494     function getModuleInstanceStateCached(node, visited) {
30495         if (visited === void 0) { visited = ts.createMap(); }
30496         var nodeId = "" + ts.getNodeId(node);
30497         if (visited.has(nodeId)) {
30498             return visited.get(nodeId) || 0 /* NonInstantiated */;
30499         }
30500         visited.set(nodeId, undefined);
30501         var result = getModuleInstanceStateWorker(node, visited);
30502         visited.set(nodeId, result);
30503         return result;
30504     }
30505     function getModuleInstanceStateWorker(node, visited) {
30506         // A module is uninstantiated if it contains only
30507         switch (node.kind) {
30508             // 1. interface declarations, type alias declarations
30509             case 246 /* InterfaceDeclaration */:
30510             case 247 /* TypeAliasDeclaration */:
30511                 return 0 /* NonInstantiated */;
30512             // 2. const enum declarations
30513             case 248 /* EnumDeclaration */:
30514                 if (ts.isEnumConst(node)) {
30515                     return 2 /* ConstEnumOnly */;
30516                 }
30517                 break;
30518             // 3. non-exported import declarations
30519             case 254 /* ImportDeclaration */:
30520             case 253 /* ImportEqualsDeclaration */:
30521                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30522                     return 0 /* NonInstantiated */;
30523                 }
30524                 break;
30525             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30526             case 260 /* ExportDeclaration */:
30527                 var exportDeclaration = node;
30528                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30529                     var state = 0 /* NonInstantiated */;
30530                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30531                         var specifier = _a[_i];
30532                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30533                         if (specifierState > state) {
30534                             state = specifierState;
30535                         }
30536                         if (state === 1 /* Instantiated */) {
30537                             return state;
30538                         }
30539                     }
30540                     return state;
30541                 }
30542                 break;
30543             // 5. other uninstantiated module declarations.
30544             case 250 /* ModuleBlock */: {
30545                 var state_1 = 0 /* NonInstantiated */;
30546                 ts.forEachChild(node, function (n) {
30547                     var childState = getModuleInstanceStateCached(n, visited);
30548                     switch (childState) {
30549                         case 0 /* NonInstantiated */:
30550                             // child is non-instantiated - continue searching
30551                             return;
30552                         case 2 /* ConstEnumOnly */:
30553                             // child is const enum only - record state and continue searching
30554                             state_1 = 2 /* ConstEnumOnly */;
30555                             return;
30556                         case 1 /* Instantiated */:
30557                             // child is instantiated - record state and stop
30558                             state_1 = 1 /* Instantiated */;
30559                             return true;
30560                         default:
30561                             ts.Debug.assertNever(childState);
30562                     }
30563                 });
30564                 return state_1;
30565             }
30566             case 249 /* ModuleDeclaration */:
30567                 return getModuleInstanceState(node, visited);
30568             case 75 /* Identifier */:
30569                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30570                 // be considered the same as type alias
30571                 if (node.isInJSDocNamespace) {
30572                     return 0 /* NonInstantiated */;
30573                 }
30574         }
30575         return 1 /* Instantiated */;
30576     }
30577     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30578         var name = specifier.propertyName || specifier.name;
30579         var p = specifier.parent;
30580         while (p) {
30581             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30582                 var statements = p.statements;
30583                 var found = void 0;
30584                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30585                     var statement = statements_1[_i];
30586                     if (ts.nodeHasName(statement, name)) {
30587                         if (!statement.parent) {
30588                             setParentPointers(p, statement);
30589                         }
30590                         var state = getModuleInstanceStateCached(statement, visited);
30591                         if (found === undefined || state > found) {
30592                             found = state;
30593                         }
30594                         if (found === 1 /* Instantiated */) {
30595                             return found;
30596                         }
30597                     }
30598                 }
30599                 if (found !== undefined) {
30600                     return found;
30601                 }
30602             }
30603             p = p.parent;
30604         }
30605         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30606     }
30607     var ContainerFlags;
30608     (function (ContainerFlags) {
30609         // The current node is not a container, and no container manipulation should happen before
30610         // recursing into it.
30611         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30612         // The current node is a container.  It should be set as the current container (and block-
30613         // container) before recursing into it.  The current node does not have locals.  Examples:
30614         //
30615         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30616         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30617         // The current node is a block-scoped-container.  It should be set as the current block-
30618         // container before recursing into it.  Examples:
30619         //
30620         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30621         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30622         // The current node is the container of a control flow path. The current control flow should
30623         // be saved and restored, and a new control flow initialized within the container.
30624         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30625         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30626         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30627         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30628         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30629         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30630     })(ContainerFlags || (ContainerFlags = {}));
30631     function initFlowNode(node) {
30632         ts.Debug.attachFlowNodeDebugInfo(node);
30633         return node;
30634     }
30635     var binder = createBinder();
30636     function bindSourceFile(file, options) {
30637         ts.performance.mark("beforeBind");
30638         ts.perfLogger.logStartBindFile("" + file.fileName);
30639         binder(file, options);
30640         ts.perfLogger.logStopBindFile();
30641         ts.performance.mark("afterBind");
30642         ts.performance.measure("Bind", "beforeBind", "afterBind");
30643     }
30644     ts.bindSourceFile = bindSourceFile;
30645     function createBinder() {
30646         var file;
30647         var options;
30648         var languageVersion;
30649         var parent;
30650         var container;
30651         var thisParentContainer; // Container one level up
30652         var blockScopeContainer;
30653         var lastContainer;
30654         var delayedTypeAliases;
30655         var seenThisKeyword;
30656         // state used by control flow analysis
30657         var currentFlow;
30658         var currentBreakTarget;
30659         var currentContinueTarget;
30660         var currentReturnTarget;
30661         var currentTrueTarget;
30662         var currentFalseTarget;
30663         var currentExceptionTarget;
30664         var preSwitchCaseFlow;
30665         var activeLabelList;
30666         var hasExplicitReturn;
30667         // state used for emit helpers
30668         var emitFlags;
30669         // If this file is an external module, then it is automatically in strict-mode according to
30670         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30671         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30672         // or if compiler options contain alwaysStrict.
30673         var inStrictMode;
30674         var symbolCount = 0;
30675         var Symbol;
30676         var classifiableNames;
30677         var unreachableFlow = { flags: 1 /* Unreachable */ };
30678         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30679         // state used to aggregate transform flags during bind.
30680         var subtreeTransformFlags = 0 /* None */;
30681         var skipTransformFlagAggregation;
30682         /**
30683          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30684          * 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)
30685          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30686          */
30687         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30688             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30689         }
30690         function bindSourceFile(f, opts) {
30691             file = f;
30692             options = opts;
30693             languageVersion = ts.getEmitScriptTarget(options);
30694             inStrictMode = bindInStrictMode(file, opts);
30695             classifiableNames = ts.createUnderscoreEscapedMap();
30696             symbolCount = 0;
30697             skipTransformFlagAggregation = file.isDeclarationFile;
30698             Symbol = ts.objectAllocator.getSymbolConstructor();
30699             // Attach debugging information if necessary
30700             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30701             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30702             if (!file.locals) {
30703                 bind(file);
30704                 file.symbolCount = symbolCount;
30705                 file.classifiableNames = classifiableNames;
30706                 delayedBindJSDocTypedefTag();
30707             }
30708             file = undefined;
30709             options = undefined;
30710             languageVersion = undefined;
30711             parent = undefined;
30712             container = undefined;
30713             thisParentContainer = undefined;
30714             blockScopeContainer = undefined;
30715             lastContainer = undefined;
30716             delayedTypeAliases = undefined;
30717             seenThisKeyword = false;
30718             currentFlow = undefined;
30719             currentBreakTarget = undefined;
30720             currentContinueTarget = undefined;
30721             currentReturnTarget = undefined;
30722             currentTrueTarget = undefined;
30723             currentFalseTarget = undefined;
30724             currentExceptionTarget = undefined;
30725             activeLabelList = undefined;
30726             hasExplicitReturn = false;
30727             emitFlags = 0 /* None */;
30728             subtreeTransformFlags = 0 /* None */;
30729         }
30730         return bindSourceFile;
30731         function bindInStrictMode(file, opts) {
30732             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30733                 // bind in strict mode source files with alwaysStrict option
30734                 return true;
30735             }
30736             else {
30737                 return !!file.externalModuleIndicator;
30738             }
30739         }
30740         function createSymbol(flags, name) {
30741             symbolCount++;
30742             return new Symbol(flags, name);
30743         }
30744         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30745             symbol.flags |= symbolFlags;
30746             node.symbol = symbol;
30747             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30748             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30749                 symbol.exports = ts.createSymbolTable();
30750             }
30751             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30752                 symbol.members = ts.createSymbolTable();
30753             }
30754             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30755             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30756                 symbol.constEnumOnlyModule = false;
30757             }
30758             if (symbolFlags & 111551 /* Value */) {
30759                 ts.setValueDeclaration(symbol, node);
30760             }
30761         }
30762         // Should not be called on a declaration with a computed property name,
30763         // unless it is a well known Symbol.
30764         function getDeclarationName(node) {
30765             if (node.kind === 259 /* ExportAssignment */) {
30766                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30767             }
30768             var name = ts.getNameOfDeclaration(node);
30769             if (name) {
30770                 if (ts.isAmbientModule(node)) {
30771                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30772                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30773                 }
30774                 if (name.kind === 154 /* ComputedPropertyName */) {
30775                     var nameExpression = name.expression;
30776                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30777                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30778                         return ts.escapeLeadingUnderscores(nameExpression.text);
30779                     }
30780                     if (ts.isSignedNumericLiteral(nameExpression)) {
30781                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30782                     }
30783                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30784                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30785                 }
30786                 if (ts.isWellKnownSymbolSyntactically(name)) {
30787                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30788                 }
30789                 if (ts.isPrivateIdentifier(name)) {
30790                     // containingClass exists because private names only allowed inside classes
30791                     var containingClass = ts.getContainingClass(node);
30792                     if (!containingClass) {
30793                         // we can get here in cases where there is already a parse error.
30794                         return undefined;
30795                     }
30796                     var containingClassSymbol = containingClass.symbol;
30797                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30798                 }
30799                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30800             }
30801             switch (node.kind) {
30802                 case 162 /* Constructor */:
30803                     return "__constructor" /* Constructor */;
30804                 case 170 /* FunctionType */:
30805                 case 165 /* CallSignature */:
30806                 case 305 /* JSDocSignature */:
30807                     return "__call" /* Call */;
30808                 case 171 /* ConstructorType */:
30809                 case 166 /* ConstructSignature */:
30810                     return "__new" /* New */;
30811                 case 167 /* IndexSignature */:
30812                     return "__index" /* Index */;
30813                 case 260 /* ExportDeclaration */:
30814                     return "__export" /* ExportStar */;
30815                 case 290 /* SourceFile */:
30816                     // json file should behave as
30817                     // module.exports = ...
30818                     return "export=" /* ExportEquals */;
30819                 case 209 /* BinaryExpression */:
30820                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30821                         // module.exports = ...
30822                         return "export=" /* ExportEquals */;
30823                     }
30824                     ts.Debug.fail("Unknown binary declaration kind");
30825                     break;
30826                 case 300 /* JSDocFunctionType */:
30827                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30828                 case 156 /* Parameter */:
30829                     // Parameters with names are handled at the top of this function.  Parameters
30830                     // without names can only come from JSDocFunctionTypes.
30831                     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"; });
30832                     var functionType = node.parent;
30833                     var index = functionType.parameters.indexOf(node);
30834                     return "arg" + index;
30835             }
30836         }
30837         function getDisplayName(node) {
30838             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
30839         }
30840         /**
30841          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
30842          * @param symbolTable - The symbol table which node will be added to.
30843          * @param parent - node's parent declaration.
30844          * @param node - The declaration to be added to the symbol table
30845          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
30846          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
30847          */
30848         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
30849             ts.Debug.assert(!ts.hasDynamicName(node));
30850             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
30851             // The exported symbol for an export default function/class node is always named "default"
30852             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
30853             var symbol;
30854             if (name === undefined) {
30855                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
30856             }
30857             else {
30858                 // Check and see if the symbol table already has a symbol with this name.  If not,
30859                 // create a new symbol with this name and add it to the table.  Note that we don't
30860                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
30861                 // with the 'excludes' flags we pass in.
30862                 //
30863                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
30864                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
30865                 // the same symbol table.  If we have a conflict, report the issue on each
30866                 // declaration we have for this symbol, and then create a new symbol for this
30867                 // declaration.
30868                 //
30869                 // Note that when properties declared in Javascript constructors
30870                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
30871                 // Always. This allows the common Javascript pattern of overwriting a prototype method
30872                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
30873                 //
30874                 // If we created a new symbol, either because we didn't have a symbol with this name
30875                 // in the symbol table, or we conflicted with an existing symbol, then just add this
30876                 // node as the sole declaration of the new symbol.
30877                 //
30878                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
30879                 // you have multiple 'vars' with the same name in the same container).  In this case
30880                 // just add this node into the declarations list of the symbol.
30881                 symbol = symbolTable.get(name);
30882                 if (includes & 2885600 /* Classifiable */) {
30883                     classifiableNames.set(name, true);
30884                 }
30885                 if (!symbol) {
30886                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30887                     if (isReplaceableByMethod)
30888                         symbol.isReplaceableByMethod = true;
30889                 }
30890                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
30891                     // A symbol already exists, so don't add this as a declaration.
30892                     return symbol;
30893                 }
30894                 else if (symbol.flags & excludes) {
30895                     if (symbol.isReplaceableByMethod) {
30896                         // Javascript constructor-declared symbols can be discarded in favor of
30897                         // prototype symbols like methods.
30898                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30899                     }
30900                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
30901                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
30902                         if (ts.isNamedDeclaration(node)) {
30903                             node.name.parent = node;
30904                         }
30905                         // Report errors every position with duplicate declaration
30906                         // Report errors on previous encountered declarations
30907                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
30908                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
30909                             : ts.Diagnostics.Duplicate_identifier_0;
30910                         var messageNeedsName_1 = true;
30911                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
30912                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
30913                             messageNeedsName_1 = false;
30914                         }
30915                         var multipleDefaultExports_1 = false;
30916                         if (ts.length(symbol.declarations)) {
30917                             // If the current node is a default export of some sort, then check if
30918                             // there are any other default exports that we need to error on.
30919                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
30920                             if (isDefaultExport) {
30921                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30922                                 messageNeedsName_1 = false;
30923                                 multipleDefaultExports_1 = true;
30924                             }
30925                             else {
30926                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
30927                                 // Error on multiple export default in the following case:
30928                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
30929                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
30930                                 if (symbol.declarations && symbol.declarations.length &&
30931                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
30932                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30933                                     messageNeedsName_1 = false;
30934                                     multipleDefaultExports_1 = true;
30935                                 }
30936                             }
30937                         }
30938                         var relatedInformation_1 = [];
30939                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
30940                             // export type T; - may have meant export type { T }?
30941                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
30942                         }
30943                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
30944                         ts.forEach(symbol.declarations, function (declaration, index) {
30945                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
30946                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
30947                             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);
30948                             if (multipleDefaultExports_1) {
30949                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
30950                             }
30951                         });
30952                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
30953                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
30954                         symbol = createSymbol(0 /* None */, name);
30955                     }
30956                 }
30957             }
30958             addDeclarationToSymbol(symbol, node, includes);
30959             if (symbol.parent) {
30960                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
30961             }
30962             else {
30963                 symbol.parent = parent;
30964             }
30965             return symbol;
30966         }
30967         function declareModuleMember(node, symbolFlags, symbolExcludes) {
30968             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
30969             if (symbolFlags & 2097152 /* Alias */) {
30970                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
30971                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
30972                 }
30973                 else {
30974                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
30975                 }
30976             }
30977             else {
30978                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
30979                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
30980                 //
30981                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
30982                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
30983                 //      with the same name in the same container.
30984                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
30985                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
30986                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
30987                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
30988                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
30989                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
30990                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
30991                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
30992                 if (ts.isJSDocTypeAlias(node))
30993                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
30994                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
30995                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
30996                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
30997                     }
30998                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
30999                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31000                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31001                     node.localSymbol = local;
31002                     return local;
31003                 }
31004                 else {
31005                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31006                 }
31007             }
31008         }
31009         // All container nodes are kept on a linked list in declaration order. This list is used by
31010         // the getLocalNameOfContainer function in the type checker to validate that the local name
31011         // used for a container is unique.
31012         function bindContainer(node, containerFlags) {
31013             // Before we recurse into a node's children, we first save the existing parent, container
31014             // and block-container.  Then after we pop out of processing the children, we restore
31015             // these saved values.
31016             var saveContainer = container;
31017             var saveThisParentContainer = thisParentContainer;
31018             var savedBlockScopeContainer = blockScopeContainer;
31019             // Depending on what kind of node this is, we may have to adjust the current container
31020             // and block-container.   If the current node is a container, then it is automatically
31021             // considered the current block-container as well.  Also, for containers that we know
31022             // may contain locals, we eagerly initialize the .locals field. We do this because
31023             // it's highly likely that the .locals will be needed to place some child in (for example,
31024             // a parameter, or variable declaration).
31025             //
31026             // However, we do not proactively create the .locals for block-containers because it's
31027             // totally normal and common for block-containers to never actually have a block-scoped
31028             // variable in them.  We don't want to end up allocating an object for every 'block' we
31029             // run into when most of them won't be necessary.
31030             //
31031             // Finally, if this is a block-container, then we clear out any existing .locals object
31032             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31033             // reusing a node from a previous compilation, that node may have had 'locals' created
31034             // for it.  We must clear this so we don't accidentally move any stale data forward from
31035             // a previous compilation.
31036             if (containerFlags & 1 /* IsContainer */) {
31037                 if (node.kind !== 202 /* ArrowFunction */) {
31038                     thisParentContainer = container;
31039                 }
31040                 container = blockScopeContainer = node;
31041                 if (containerFlags & 32 /* HasLocals */) {
31042                     container.locals = ts.createSymbolTable();
31043                 }
31044                 addToContainerChain(container);
31045             }
31046             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31047                 blockScopeContainer = node;
31048                 blockScopeContainer.locals = undefined;
31049             }
31050             if (containerFlags & 4 /* IsControlFlowContainer */) {
31051                 var saveCurrentFlow = currentFlow;
31052                 var saveBreakTarget = currentBreakTarget;
31053                 var saveContinueTarget = currentContinueTarget;
31054                 var saveReturnTarget = currentReturnTarget;
31055                 var saveExceptionTarget = currentExceptionTarget;
31056                 var saveActiveLabelList = activeLabelList;
31057                 var saveHasExplicitReturn = hasExplicitReturn;
31058                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31059                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31060                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31061                 // similarly to break statements that exit to a label just past the statement body.
31062                 if (!isIIFE) {
31063                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31064                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31065                         currentFlow.node = node;
31066                     }
31067                 }
31068                 // We create a return control flow graph for IIFEs and constructors. For constructors
31069                 // we use the return control flow graph in strict property initialization checks.
31070                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31071                 currentExceptionTarget = undefined;
31072                 currentBreakTarget = undefined;
31073                 currentContinueTarget = undefined;
31074                 activeLabelList = undefined;
31075                 hasExplicitReturn = false;
31076                 bindChildren(node);
31077                 // Reset all reachability check related flags on node (for incremental scenarios)
31078                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31079                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31080                     node.flags |= 256 /* HasImplicitReturn */;
31081                     if (hasExplicitReturn)
31082                         node.flags |= 512 /* HasExplicitReturn */;
31083                     node.endFlowNode = currentFlow;
31084                 }
31085                 if (node.kind === 290 /* SourceFile */) {
31086                     node.flags |= emitFlags;
31087                 }
31088                 if (currentReturnTarget) {
31089                     addAntecedent(currentReturnTarget, currentFlow);
31090                     currentFlow = finishFlowLabel(currentReturnTarget);
31091                     if (node.kind === 162 /* Constructor */) {
31092                         node.returnFlowNode = currentFlow;
31093                     }
31094                 }
31095                 if (!isIIFE) {
31096                     currentFlow = saveCurrentFlow;
31097                 }
31098                 currentBreakTarget = saveBreakTarget;
31099                 currentContinueTarget = saveContinueTarget;
31100                 currentReturnTarget = saveReturnTarget;
31101                 currentExceptionTarget = saveExceptionTarget;
31102                 activeLabelList = saveActiveLabelList;
31103                 hasExplicitReturn = saveHasExplicitReturn;
31104             }
31105             else if (containerFlags & 64 /* IsInterface */) {
31106                 seenThisKeyword = false;
31107                 bindChildren(node);
31108                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31109             }
31110             else {
31111                 bindChildren(node);
31112             }
31113             container = saveContainer;
31114             thisParentContainer = saveThisParentContainer;
31115             blockScopeContainer = savedBlockScopeContainer;
31116         }
31117         function bindChildren(node) {
31118             if (skipTransformFlagAggregation) {
31119                 bindChildrenWorker(node);
31120             }
31121             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31122                 skipTransformFlagAggregation = true;
31123                 bindChildrenWorker(node);
31124                 skipTransformFlagAggregation = false;
31125                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31126             }
31127             else {
31128                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31129                 subtreeTransformFlags = 0;
31130                 bindChildrenWorker(node);
31131                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31132             }
31133         }
31134         function bindEachFunctionsFirst(nodes) {
31135             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31136             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31137         }
31138         function bindEach(nodes, bindFunction) {
31139             if (bindFunction === void 0) { bindFunction = bind; }
31140             if (nodes === undefined) {
31141                 return;
31142             }
31143             if (skipTransformFlagAggregation) {
31144                 ts.forEach(nodes, bindFunction);
31145             }
31146             else {
31147                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31148                 subtreeTransformFlags = 0 /* None */;
31149                 var nodeArrayFlags = 0 /* None */;
31150                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31151                     var node = nodes_2[_i];
31152                     bindFunction(node);
31153                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31154                 }
31155                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31156                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31157             }
31158         }
31159         function bindEachChild(node) {
31160             ts.forEachChild(node, bind, bindEach);
31161         }
31162         function bindChildrenWorker(node) {
31163             if (checkUnreachable(node)) {
31164                 bindEachChild(node);
31165                 bindJSDoc(node);
31166                 return;
31167             }
31168             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31169                 node.flowNode = currentFlow;
31170             }
31171             switch (node.kind) {
31172                 case 229 /* WhileStatement */:
31173                     bindWhileStatement(node);
31174                     break;
31175                 case 228 /* DoStatement */:
31176                     bindDoStatement(node);
31177                     break;
31178                 case 230 /* ForStatement */:
31179                     bindForStatement(node);
31180                     break;
31181                 case 231 /* ForInStatement */:
31182                 case 232 /* ForOfStatement */:
31183                     bindForInOrForOfStatement(node);
31184                     break;
31185                 case 227 /* IfStatement */:
31186                     bindIfStatement(node);
31187                     break;
31188                 case 235 /* ReturnStatement */:
31189                 case 239 /* ThrowStatement */:
31190                     bindReturnOrThrow(node);
31191                     break;
31192                 case 234 /* BreakStatement */:
31193                 case 233 /* ContinueStatement */:
31194                     bindBreakOrContinueStatement(node);
31195                     break;
31196                 case 240 /* TryStatement */:
31197                     bindTryStatement(node);
31198                     break;
31199                 case 237 /* SwitchStatement */:
31200                     bindSwitchStatement(node);
31201                     break;
31202                 case 251 /* CaseBlock */:
31203                     bindCaseBlock(node);
31204                     break;
31205                 case 277 /* CaseClause */:
31206                     bindCaseClause(node);
31207                     break;
31208                 case 226 /* ExpressionStatement */:
31209                     bindExpressionStatement(node);
31210                     break;
31211                 case 238 /* LabeledStatement */:
31212                     bindLabeledStatement(node);
31213                     break;
31214                 case 207 /* PrefixUnaryExpression */:
31215                     bindPrefixUnaryExpressionFlow(node);
31216                     break;
31217                 case 208 /* PostfixUnaryExpression */:
31218                     bindPostfixUnaryExpressionFlow(node);
31219                     break;
31220                 case 209 /* BinaryExpression */:
31221                     bindBinaryExpressionFlow(node);
31222                     break;
31223                 case 203 /* DeleteExpression */:
31224                     bindDeleteExpressionFlow(node);
31225                     break;
31226                 case 210 /* ConditionalExpression */:
31227                     bindConditionalExpressionFlow(node);
31228                     break;
31229                 case 242 /* VariableDeclaration */:
31230                     bindVariableDeclarationFlow(node);
31231                     break;
31232                 case 194 /* PropertyAccessExpression */:
31233                 case 195 /* ElementAccessExpression */:
31234                     bindAccessExpressionFlow(node);
31235                     break;
31236                 case 196 /* CallExpression */:
31237                     bindCallExpressionFlow(node);
31238                     break;
31239                 case 218 /* NonNullExpression */:
31240                     bindNonNullExpressionFlow(node);
31241                     break;
31242                 case 322 /* JSDocTypedefTag */:
31243                 case 315 /* JSDocCallbackTag */:
31244                 case 316 /* JSDocEnumTag */:
31245                     bindJSDocTypeAlias(node);
31246                     break;
31247                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31248                 case 290 /* SourceFile */: {
31249                     bindEachFunctionsFirst(node.statements);
31250                     bind(node.endOfFileToken);
31251                     break;
31252                 }
31253                 case 223 /* Block */:
31254                 case 250 /* ModuleBlock */:
31255                     bindEachFunctionsFirst(node.statements);
31256                     break;
31257                 default:
31258                     bindEachChild(node);
31259                     break;
31260             }
31261             bindJSDoc(node);
31262         }
31263         function isNarrowingExpression(expr) {
31264             switch (expr.kind) {
31265                 case 75 /* Identifier */:
31266                 case 104 /* ThisKeyword */:
31267                 case 194 /* PropertyAccessExpression */:
31268                 case 195 /* ElementAccessExpression */:
31269                     return containsNarrowableReference(expr);
31270                 case 196 /* CallExpression */:
31271                     return hasNarrowableArgument(expr);
31272                 case 200 /* ParenthesizedExpression */:
31273                     return isNarrowingExpression(expr.expression);
31274                 case 209 /* BinaryExpression */:
31275                     return isNarrowingBinaryExpression(expr);
31276                 case 207 /* PrefixUnaryExpression */:
31277                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31278                 case 204 /* TypeOfExpression */:
31279                     return isNarrowingExpression(expr.expression);
31280             }
31281             return false;
31282         }
31283         function isNarrowableReference(expr) {
31284             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31285                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31286                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31287         }
31288         function containsNarrowableReference(expr) {
31289             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31290         }
31291         function hasNarrowableArgument(expr) {
31292             if (expr.arguments) {
31293                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31294                     var argument = _a[_i];
31295                     if (containsNarrowableReference(argument)) {
31296                         return true;
31297                     }
31298                 }
31299             }
31300             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31301                 containsNarrowableReference(expr.expression.expression)) {
31302                 return true;
31303             }
31304             return false;
31305         }
31306         function isNarrowingTypeofOperands(expr1, expr2) {
31307             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31308         }
31309         function isNarrowableInOperands(left, right) {
31310             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31311         }
31312         function isNarrowingBinaryExpression(expr) {
31313             switch (expr.operatorToken.kind) {
31314                 case 62 /* EqualsToken */:
31315                     return containsNarrowableReference(expr.left);
31316                 case 34 /* EqualsEqualsToken */:
31317                 case 35 /* ExclamationEqualsToken */:
31318                 case 36 /* EqualsEqualsEqualsToken */:
31319                 case 37 /* ExclamationEqualsEqualsToken */:
31320                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31321                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31322                 case 98 /* InstanceOfKeyword */:
31323                     return isNarrowableOperand(expr.left);
31324                 case 97 /* InKeyword */:
31325                     return isNarrowableInOperands(expr.left, expr.right);
31326                 case 27 /* CommaToken */:
31327                     return isNarrowingExpression(expr.right);
31328             }
31329             return false;
31330         }
31331         function isNarrowableOperand(expr) {
31332             switch (expr.kind) {
31333                 case 200 /* ParenthesizedExpression */:
31334                     return isNarrowableOperand(expr.expression);
31335                 case 209 /* BinaryExpression */:
31336                     switch (expr.operatorToken.kind) {
31337                         case 62 /* EqualsToken */:
31338                             return isNarrowableOperand(expr.left);
31339                         case 27 /* CommaToken */:
31340                             return isNarrowableOperand(expr.right);
31341                     }
31342             }
31343             return containsNarrowableReference(expr);
31344         }
31345         function createBranchLabel() {
31346             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31347         }
31348         function createLoopLabel() {
31349             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31350         }
31351         function createReduceLabel(target, antecedents, antecedent) {
31352             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31353         }
31354         function setFlowNodeReferenced(flow) {
31355             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31356             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31357         }
31358         function addAntecedent(label, antecedent) {
31359             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31360                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31361                 setFlowNodeReferenced(antecedent);
31362             }
31363         }
31364         function createFlowCondition(flags, antecedent, expression) {
31365             if (antecedent.flags & 1 /* Unreachable */) {
31366                 return antecedent;
31367             }
31368             if (!expression) {
31369                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31370             }
31371             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31372                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31373                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31374                 return unreachableFlow;
31375             }
31376             if (!isNarrowingExpression(expression)) {
31377                 return antecedent;
31378             }
31379             setFlowNodeReferenced(antecedent);
31380             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31381         }
31382         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31383             setFlowNodeReferenced(antecedent);
31384             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31385         }
31386         function createFlowMutation(flags, antecedent, node) {
31387             setFlowNodeReferenced(antecedent);
31388             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31389             if (currentExceptionTarget) {
31390                 addAntecedent(currentExceptionTarget, result);
31391             }
31392             return result;
31393         }
31394         function createFlowCall(antecedent, node) {
31395             setFlowNodeReferenced(antecedent);
31396             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31397         }
31398         function finishFlowLabel(flow) {
31399             var antecedents = flow.antecedents;
31400             if (!antecedents) {
31401                 return unreachableFlow;
31402             }
31403             if (antecedents.length === 1) {
31404                 return antecedents[0];
31405             }
31406             return flow;
31407         }
31408         function isStatementCondition(node) {
31409             var parent = node.parent;
31410             switch (parent.kind) {
31411                 case 227 /* IfStatement */:
31412                 case 229 /* WhileStatement */:
31413                 case 228 /* DoStatement */:
31414                     return parent.expression === node;
31415                 case 230 /* ForStatement */:
31416                 case 210 /* ConditionalExpression */:
31417                     return parent.condition === node;
31418             }
31419             return false;
31420         }
31421         function isLogicalExpression(node) {
31422             while (true) {
31423                 if (node.kind === 200 /* ParenthesizedExpression */) {
31424                     node = node.expression;
31425                 }
31426                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31427                     node = node.operand;
31428                 }
31429                 else {
31430                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31431                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31432                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31433                 }
31434             }
31435         }
31436         function isTopLevelLogicalExpression(node) {
31437             while (ts.isParenthesizedExpression(node.parent) ||
31438                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31439                 node = node.parent;
31440             }
31441             return !isStatementCondition(node) &&
31442                 !isLogicalExpression(node.parent) &&
31443                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31444         }
31445         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31446             var savedTrueTarget = currentTrueTarget;
31447             var savedFalseTarget = currentFalseTarget;
31448             currentTrueTarget = trueTarget;
31449             currentFalseTarget = falseTarget;
31450             action(value);
31451             currentTrueTarget = savedTrueTarget;
31452             currentFalseTarget = savedFalseTarget;
31453         }
31454         function bindCondition(node, trueTarget, falseTarget) {
31455             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31456             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31457                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31458                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31459             }
31460         }
31461         function bindIterativeStatement(node, breakTarget, continueTarget) {
31462             var saveBreakTarget = currentBreakTarget;
31463             var saveContinueTarget = currentContinueTarget;
31464             currentBreakTarget = breakTarget;
31465             currentContinueTarget = continueTarget;
31466             bind(node);
31467             currentBreakTarget = saveBreakTarget;
31468             currentContinueTarget = saveContinueTarget;
31469         }
31470         function setContinueTarget(node, target) {
31471             var label = activeLabelList;
31472             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31473                 label.continueTarget = target;
31474                 label = label.next;
31475                 node = node.parent;
31476             }
31477             return target;
31478         }
31479         function bindWhileStatement(node) {
31480             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31481             var preBodyLabel = createBranchLabel();
31482             var postWhileLabel = createBranchLabel();
31483             addAntecedent(preWhileLabel, currentFlow);
31484             currentFlow = preWhileLabel;
31485             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31486             currentFlow = finishFlowLabel(preBodyLabel);
31487             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31488             addAntecedent(preWhileLabel, currentFlow);
31489             currentFlow = finishFlowLabel(postWhileLabel);
31490         }
31491         function bindDoStatement(node) {
31492             var preDoLabel = createLoopLabel();
31493             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31494             var postDoLabel = createBranchLabel();
31495             addAntecedent(preDoLabel, currentFlow);
31496             currentFlow = preDoLabel;
31497             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31498             addAntecedent(preConditionLabel, currentFlow);
31499             currentFlow = finishFlowLabel(preConditionLabel);
31500             bindCondition(node.expression, preDoLabel, postDoLabel);
31501             currentFlow = finishFlowLabel(postDoLabel);
31502         }
31503         function bindForStatement(node) {
31504             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31505             var preBodyLabel = createBranchLabel();
31506             var postLoopLabel = createBranchLabel();
31507             bind(node.initializer);
31508             addAntecedent(preLoopLabel, currentFlow);
31509             currentFlow = preLoopLabel;
31510             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31511             currentFlow = finishFlowLabel(preBodyLabel);
31512             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31513             bind(node.incrementor);
31514             addAntecedent(preLoopLabel, currentFlow);
31515             currentFlow = finishFlowLabel(postLoopLabel);
31516         }
31517         function bindForInOrForOfStatement(node) {
31518             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31519             var postLoopLabel = createBranchLabel();
31520             bind(node.expression);
31521             addAntecedent(preLoopLabel, currentFlow);
31522             currentFlow = preLoopLabel;
31523             if (node.kind === 232 /* ForOfStatement */) {
31524                 bind(node.awaitModifier);
31525             }
31526             addAntecedent(postLoopLabel, currentFlow);
31527             bind(node.initializer);
31528             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31529                 bindAssignmentTargetFlow(node.initializer);
31530             }
31531             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31532             addAntecedent(preLoopLabel, currentFlow);
31533             currentFlow = finishFlowLabel(postLoopLabel);
31534         }
31535         function bindIfStatement(node) {
31536             var thenLabel = createBranchLabel();
31537             var elseLabel = createBranchLabel();
31538             var postIfLabel = createBranchLabel();
31539             bindCondition(node.expression, thenLabel, elseLabel);
31540             currentFlow = finishFlowLabel(thenLabel);
31541             bind(node.thenStatement);
31542             addAntecedent(postIfLabel, currentFlow);
31543             currentFlow = finishFlowLabel(elseLabel);
31544             bind(node.elseStatement);
31545             addAntecedent(postIfLabel, currentFlow);
31546             currentFlow = finishFlowLabel(postIfLabel);
31547         }
31548         function bindReturnOrThrow(node) {
31549             bind(node.expression);
31550             if (node.kind === 235 /* ReturnStatement */) {
31551                 hasExplicitReturn = true;
31552                 if (currentReturnTarget) {
31553                     addAntecedent(currentReturnTarget, currentFlow);
31554                 }
31555             }
31556             currentFlow = unreachableFlow;
31557         }
31558         function findActiveLabel(name) {
31559             for (var label = activeLabelList; label; label = label.next) {
31560                 if (label.name === name) {
31561                     return label;
31562                 }
31563             }
31564             return undefined;
31565         }
31566         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31567             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31568             if (flowLabel) {
31569                 addAntecedent(flowLabel, currentFlow);
31570                 currentFlow = unreachableFlow;
31571             }
31572         }
31573         function bindBreakOrContinueStatement(node) {
31574             bind(node.label);
31575             if (node.label) {
31576                 var activeLabel = findActiveLabel(node.label.escapedText);
31577                 if (activeLabel) {
31578                     activeLabel.referenced = true;
31579                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31580                 }
31581             }
31582             else {
31583                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31584             }
31585         }
31586         function bindTryStatement(node) {
31587             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31588             // to track code that causes mutations (because only mutations widen the possible control flow type of
31589             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31590             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31591             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31592             // represent exceptions that occur before any mutations.
31593             var saveReturnTarget = currentReturnTarget;
31594             var saveExceptionTarget = currentExceptionTarget;
31595             var normalExitLabel = createBranchLabel();
31596             var returnLabel = createBranchLabel();
31597             var exceptionLabel = createBranchLabel();
31598             if (node.finallyBlock) {
31599                 currentReturnTarget = returnLabel;
31600             }
31601             addAntecedent(exceptionLabel, currentFlow);
31602             currentExceptionTarget = exceptionLabel;
31603             bind(node.tryBlock);
31604             addAntecedent(normalExitLabel, currentFlow);
31605             if (node.catchClause) {
31606                 // Start of catch clause is the target of exceptions from try block.
31607                 currentFlow = finishFlowLabel(exceptionLabel);
31608                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31609                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31610                 // acts like a second try block.
31611                 exceptionLabel = createBranchLabel();
31612                 addAntecedent(exceptionLabel, currentFlow);
31613                 currentExceptionTarget = exceptionLabel;
31614                 bind(node.catchClause);
31615                 addAntecedent(normalExitLabel, currentFlow);
31616             }
31617             currentReturnTarget = saveReturnTarget;
31618             currentExceptionTarget = saveExceptionTarget;
31619             if (node.finallyBlock) {
31620                 // Possible ways control can reach the finally block:
31621                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31622                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31623                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31624                 // 4) Exception in try block of a try-finally
31625                 // 5) Exception in catch block of a try-catch-finally
31626                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31627                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31628                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31629                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31630                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31631                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31632                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31633                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31634                 var finallyLabel = createBranchLabel();
31635                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31636                 currentFlow = finallyLabel;
31637                 bind(node.finallyBlock);
31638                 if (currentFlow.flags & 1 /* Unreachable */) {
31639                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31640                     currentFlow = unreachableFlow;
31641                 }
31642                 else {
31643                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31644                     // flow that goes back through the finally block and back through only the return statements.
31645                     if (currentReturnTarget && returnLabel.antecedents) {
31646                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31647                     }
31648                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31649                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31650                     // result in an unreachable current control flow.
31651                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31652                 }
31653             }
31654             else {
31655                 currentFlow = finishFlowLabel(normalExitLabel);
31656             }
31657         }
31658         function bindSwitchStatement(node) {
31659             var postSwitchLabel = createBranchLabel();
31660             bind(node.expression);
31661             var saveBreakTarget = currentBreakTarget;
31662             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31663             currentBreakTarget = postSwitchLabel;
31664             preSwitchCaseFlow = currentFlow;
31665             bind(node.caseBlock);
31666             addAntecedent(postSwitchLabel, currentFlow);
31667             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31668             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31669             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31670             // this property in control flow analysis, it's there only for backwards compatibility.
31671             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31672             if (!hasDefault) {
31673                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31674             }
31675             currentBreakTarget = saveBreakTarget;
31676             preSwitchCaseFlow = savePreSwitchCaseFlow;
31677             currentFlow = finishFlowLabel(postSwitchLabel);
31678         }
31679         function bindCaseBlock(node) {
31680             var savedSubtreeTransformFlags = subtreeTransformFlags;
31681             subtreeTransformFlags = 0;
31682             var clauses = node.clauses;
31683             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31684             var fallthroughFlow = unreachableFlow;
31685             for (var i = 0; i < clauses.length; i++) {
31686                 var clauseStart = i;
31687                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31688                     bind(clauses[i]);
31689                     i++;
31690                 }
31691                 var preCaseLabel = createBranchLabel();
31692                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31693                 addAntecedent(preCaseLabel, fallthroughFlow);
31694                 currentFlow = finishFlowLabel(preCaseLabel);
31695                 var clause = clauses[i];
31696                 bind(clause);
31697                 fallthroughFlow = currentFlow;
31698                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31699                     clause.fallthroughFlowNode = currentFlow;
31700                 }
31701             }
31702             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31703             subtreeTransformFlags |= savedSubtreeTransformFlags;
31704         }
31705         function bindCaseClause(node) {
31706             var saveCurrentFlow = currentFlow;
31707             currentFlow = preSwitchCaseFlow;
31708             bind(node.expression);
31709             currentFlow = saveCurrentFlow;
31710             bindEach(node.statements);
31711         }
31712         function bindExpressionStatement(node) {
31713             bind(node.expression);
31714             // A top level call expression with a dotted function name and at least one argument
31715             // is potentially an assertion and is therefore included in the control flow.
31716             if (node.expression.kind === 196 /* CallExpression */) {
31717                 var call = node.expression;
31718                 if (ts.isDottedName(call.expression)) {
31719                     currentFlow = createFlowCall(currentFlow, call);
31720                 }
31721             }
31722         }
31723         function bindLabeledStatement(node) {
31724             var postStatementLabel = createBranchLabel();
31725             activeLabelList = {
31726                 next: activeLabelList,
31727                 name: node.label.escapedText,
31728                 breakTarget: postStatementLabel,
31729                 continueTarget: undefined,
31730                 referenced: false
31731             };
31732             bind(node.label);
31733             bind(node.statement);
31734             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31735                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31736             }
31737             activeLabelList = activeLabelList.next;
31738             addAntecedent(postStatementLabel, currentFlow);
31739             currentFlow = finishFlowLabel(postStatementLabel);
31740         }
31741         function bindDestructuringTargetFlow(node) {
31742             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31743                 bindAssignmentTargetFlow(node.left);
31744             }
31745             else {
31746                 bindAssignmentTargetFlow(node);
31747             }
31748         }
31749         function bindAssignmentTargetFlow(node) {
31750             if (isNarrowableReference(node)) {
31751                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31752             }
31753             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31754                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31755                     var e = _a[_i];
31756                     if (e.kind === 213 /* SpreadElement */) {
31757                         bindAssignmentTargetFlow(e.expression);
31758                     }
31759                     else {
31760                         bindDestructuringTargetFlow(e);
31761                     }
31762                 }
31763             }
31764             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31765                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31766                     var p = _c[_b];
31767                     if (p.kind === 281 /* PropertyAssignment */) {
31768                         bindDestructuringTargetFlow(p.initializer);
31769                     }
31770                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31771                         bindAssignmentTargetFlow(p.name);
31772                     }
31773                     else if (p.kind === 283 /* SpreadAssignment */) {
31774                         bindAssignmentTargetFlow(p.expression);
31775                     }
31776                 }
31777             }
31778         }
31779         function bindLogicalExpression(node, trueTarget, falseTarget) {
31780             var preRightLabel = createBranchLabel();
31781             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31782                 bindCondition(node.left, preRightLabel, falseTarget);
31783             }
31784             else {
31785                 bindCondition(node.left, trueTarget, preRightLabel);
31786             }
31787             currentFlow = finishFlowLabel(preRightLabel);
31788             bind(node.operatorToken);
31789             bindCondition(node.right, trueTarget, falseTarget);
31790         }
31791         function bindPrefixUnaryExpressionFlow(node) {
31792             if (node.operator === 53 /* ExclamationToken */) {
31793                 var saveTrueTarget = currentTrueTarget;
31794                 currentTrueTarget = currentFalseTarget;
31795                 currentFalseTarget = saveTrueTarget;
31796                 bindEachChild(node);
31797                 currentFalseTarget = currentTrueTarget;
31798                 currentTrueTarget = saveTrueTarget;
31799             }
31800             else {
31801                 bindEachChild(node);
31802                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31803                     bindAssignmentTargetFlow(node.operand);
31804                 }
31805             }
31806         }
31807         function bindPostfixUnaryExpressionFlow(node) {
31808             bindEachChild(node);
31809             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31810                 bindAssignmentTargetFlow(node.operand);
31811             }
31812         }
31813         var BindBinaryExpressionFlowState;
31814         (function (BindBinaryExpressionFlowState) {
31815             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31816             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31817             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31818             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31819             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31820         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31821         function bindBinaryExpressionFlow(node) {
31822             var workStacks = {
31823                 expr: [node],
31824                 state: [1 /* MaybeBindLeft */],
31825                 inStrictMode: [undefined],
31826                 parent: [undefined],
31827                 subtreeFlags: [undefined]
31828             };
31829             var stackIndex = 0;
31830             while (stackIndex >= 0) {
31831                 node = workStacks.expr[stackIndex];
31832                 switch (workStacks.state[stackIndex]) {
31833                     case 0 /* BindThenBindChildren */: {
31834                         // This state is used only when recuring, to emulate the work that `bind` does before
31835                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31836                         node.parent = parent;
31837                         var saveInStrictMode = inStrictMode;
31838                         bindWorker(node);
31839                         var saveParent = parent;
31840                         parent = node;
31841                         var subtreeFlagsState = void 0;
31842                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
31843                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
31844                         if (skipTransformFlagAggregation) {
31845                             // do nothing extra
31846                         }
31847                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31848                             skipTransformFlagAggregation = true;
31849                             subtreeFlagsState = -1;
31850                         }
31851                         else {
31852                             var savedSubtreeTransformFlags = subtreeTransformFlags;
31853                             subtreeTransformFlags = 0;
31854                             subtreeFlagsState = savedSubtreeTransformFlags;
31855                         }
31856                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
31857                         break;
31858                     }
31859                     case 1 /* MaybeBindLeft */: {
31860                         var operator = node.operatorToken.kind;
31861                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
31862                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
31863                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
31864                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
31865                             if (isTopLevelLogicalExpression(node)) {
31866                                 var postExpressionLabel = createBranchLabel();
31867                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
31868                                 currentFlow = finishFlowLabel(postExpressionLabel);
31869                             }
31870                             else {
31871                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
31872                             }
31873                             completeNode();
31874                         }
31875                         else {
31876                             advanceState(2 /* BindToken */);
31877                             maybeBind(node.left);
31878                         }
31879                         break;
31880                     }
31881                     case 2 /* BindToken */: {
31882                         advanceState(3 /* BindRight */);
31883                         maybeBind(node.operatorToken);
31884                         break;
31885                     }
31886                     case 3 /* BindRight */: {
31887                         advanceState(4 /* FinishBind */);
31888                         maybeBind(node.right);
31889                         break;
31890                     }
31891                     case 4 /* FinishBind */: {
31892                         var operator = node.operatorToken.kind;
31893                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
31894                             bindAssignmentTargetFlow(node.left);
31895                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
31896                                 var elementAccess = node.left;
31897                                 if (isNarrowableOperand(elementAccess.expression)) {
31898                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
31899                                 }
31900                             }
31901                         }
31902                         completeNode();
31903                         break;
31904                     }
31905                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
31906                 }
31907             }
31908             /**
31909              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
31910              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
31911              */
31912             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
31913                 workStacks.state[stackIndex] = state;
31914                 if (isInStrictMode !== undefined) {
31915                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
31916                 }
31917                 if (parent !== undefined) {
31918                     workStacks.parent[stackIndex] = parent;
31919                 }
31920                 if (subtreeFlags !== undefined) {
31921                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
31922                 }
31923             }
31924             function completeNode() {
31925                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
31926                     if (workStacks.subtreeFlags[stackIndex] === -1) {
31927                         skipTransformFlagAggregation = false;
31928                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31929                     }
31930                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
31931                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
31932                     }
31933                     inStrictMode = workStacks.inStrictMode[stackIndex];
31934                     parent = workStacks.parent[stackIndex];
31935                 }
31936                 stackIndex--;
31937             }
31938             /**
31939              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
31940              */
31941             function maybeBind(node) {
31942                 if (node && ts.isBinaryExpression(node)) {
31943                     stackIndex++;
31944                     workStacks.expr[stackIndex] = node;
31945                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
31946                     workStacks.inStrictMode[stackIndex] = undefined;
31947                     workStacks.parent[stackIndex] = undefined;
31948                     workStacks.subtreeFlags[stackIndex] = undefined;
31949                 }
31950                 else {
31951                     bind(node);
31952                 }
31953             }
31954         }
31955         function bindDeleteExpressionFlow(node) {
31956             bindEachChild(node);
31957             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
31958                 bindAssignmentTargetFlow(node.expression);
31959             }
31960         }
31961         function bindConditionalExpressionFlow(node) {
31962             var trueLabel = createBranchLabel();
31963             var falseLabel = createBranchLabel();
31964             var postExpressionLabel = createBranchLabel();
31965             bindCondition(node.condition, trueLabel, falseLabel);
31966             currentFlow = finishFlowLabel(trueLabel);
31967             bind(node.questionToken);
31968             bind(node.whenTrue);
31969             addAntecedent(postExpressionLabel, currentFlow);
31970             currentFlow = finishFlowLabel(falseLabel);
31971             bind(node.colonToken);
31972             bind(node.whenFalse);
31973             addAntecedent(postExpressionLabel, currentFlow);
31974             currentFlow = finishFlowLabel(postExpressionLabel);
31975         }
31976         function bindInitializedVariableFlow(node) {
31977             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
31978             if (ts.isBindingPattern(name)) {
31979                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
31980                     var child = _a[_i];
31981                     bindInitializedVariableFlow(child);
31982                 }
31983             }
31984             else {
31985                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31986             }
31987         }
31988         function bindVariableDeclarationFlow(node) {
31989             bindEachChild(node);
31990             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
31991                 bindInitializedVariableFlow(node);
31992             }
31993         }
31994         function bindJSDocTypeAlias(node) {
31995             node.tagName.parent = node;
31996             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
31997                 setParentPointers(node, node.fullName);
31998             }
31999         }
32000         function bindJSDocClassTag(node) {
32001             bindEachChild(node);
32002             var host = ts.getHostSignatureFromJSDoc(node);
32003             if (host && host.kind !== 161 /* MethodDeclaration */) {
32004                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32005             }
32006         }
32007         function bindOptionalExpression(node, trueTarget, falseTarget) {
32008             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32009             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32010                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32011                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32012             }
32013         }
32014         function bindOptionalChainRest(node) {
32015             switch (node.kind) {
32016                 case 194 /* PropertyAccessExpression */:
32017                     bind(node.questionDotToken);
32018                     bind(node.name);
32019                     break;
32020                 case 195 /* ElementAccessExpression */:
32021                     bind(node.questionDotToken);
32022                     bind(node.argumentExpression);
32023                     break;
32024                 case 196 /* CallExpression */:
32025                     bind(node.questionDotToken);
32026                     bindEach(node.typeArguments);
32027                     bindEach(node.arguments);
32028                     break;
32029             }
32030         }
32031         function bindOptionalChain(node, trueTarget, falseTarget) {
32032             // For an optional chain, we emulate the behavior of a logical expression:
32033             //
32034             // a?.b         -> a && a.b
32035             // a?.b.c       -> a && a.b.c
32036             // a?.b?.c      -> a && a.b && a.b.c
32037             // a?.[x = 1]   -> a && a[x = 1]
32038             //
32039             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32040             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32041             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32042             // chain node. We then treat the entire node as the right side of the expression.
32043             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32044             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32045             if (preChainLabel) {
32046                 currentFlow = finishFlowLabel(preChainLabel);
32047             }
32048             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32049             if (ts.isOutermostOptionalChain(node)) {
32050                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32051                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32052             }
32053         }
32054         function bindOptionalChainFlow(node) {
32055             if (isTopLevelLogicalExpression(node)) {
32056                 var postExpressionLabel = createBranchLabel();
32057                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32058                 currentFlow = finishFlowLabel(postExpressionLabel);
32059             }
32060             else {
32061                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32062             }
32063         }
32064         function bindNonNullExpressionFlow(node) {
32065             if (ts.isOptionalChain(node)) {
32066                 bindOptionalChainFlow(node);
32067             }
32068             else {
32069                 bindEachChild(node);
32070             }
32071         }
32072         function bindAccessExpressionFlow(node) {
32073             if (ts.isOptionalChain(node)) {
32074                 bindOptionalChainFlow(node);
32075             }
32076             else {
32077                 bindEachChild(node);
32078             }
32079         }
32080         function bindCallExpressionFlow(node) {
32081             if (ts.isOptionalChain(node)) {
32082                 bindOptionalChainFlow(node);
32083             }
32084             else {
32085                 // If the target of the call expression is a function expression or arrow function we have
32086                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32087                 // the current control flow (which includes evaluation of the IIFE arguments).
32088                 var expr = ts.skipParentheses(node.expression);
32089                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32090                     bindEach(node.typeArguments);
32091                     bindEach(node.arguments);
32092                     bind(node.expression);
32093                 }
32094                 else {
32095                     bindEachChild(node);
32096                 }
32097             }
32098             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32099                 var propertyAccess = node.expression;
32100                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32101                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32102                 }
32103             }
32104         }
32105         function getContainerFlags(node) {
32106             switch (node.kind) {
32107                 case 214 /* ClassExpression */:
32108                 case 245 /* ClassDeclaration */:
32109                 case 248 /* EnumDeclaration */:
32110                 case 193 /* ObjectLiteralExpression */:
32111                 case 173 /* TypeLiteral */:
32112                 case 304 /* JSDocTypeLiteral */:
32113                 case 274 /* JsxAttributes */:
32114                     return 1 /* IsContainer */;
32115                 case 246 /* InterfaceDeclaration */:
32116                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32117                 case 249 /* ModuleDeclaration */:
32118                 case 247 /* TypeAliasDeclaration */:
32119                 case 186 /* MappedType */:
32120                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32121                 case 290 /* SourceFile */:
32122                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32123                 case 161 /* MethodDeclaration */:
32124                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32125                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32126                     }
32127                 // falls through
32128                 case 162 /* Constructor */:
32129                 case 244 /* FunctionDeclaration */:
32130                 case 160 /* MethodSignature */:
32131                 case 163 /* GetAccessor */:
32132                 case 164 /* SetAccessor */:
32133                 case 165 /* CallSignature */:
32134                 case 305 /* JSDocSignature */:
32135                 case 300 /* JSDocFunctionType */:
32136                 case 170 /* FunctionType */:
32137                 case 166 /* ConstructSignature */:
32138                 case 167 /* IndexSignature */:
32139                 case 171 /* ConstructorType */:
32140                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32141                 case 201 /* FunctionExpression */:
32142                 case 202 /* ArrowFunction */:
32143                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32144                 case 250 /* ModuleBlock */:
32145                     return 4 /* IsControlFlowContainer */;
32146                 case 159 /* PropertyDeclaration */:
32147                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32148                 case 280 /* CatchClause */:
32149                 case 230 /* ForStatement */:
32150                 case 231 /* ForInStatement */:
32151                 case 232 /* ForOfStatement */:
32152                 case 251 /* CaseBlock */:
32153                     return 2 /* IsBlockScopedContainer */;
32154                 case 223 /* Block */:
32155                     // do not treat blocks directly inside a function as a block-scoped-container.
32156                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32157                     // would not appear to be a redeclaration of a block scoped local in the following
32158                     // example:
32159                     //
32160                     //      function foo() {
32161                     //          var x;
32162                     //          let x;
32163                     //      }
32164                     //
32165                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32166                     // the block, then there would be no collision.
32167                     //
32168                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32169                     // and 'let x' go into the Function-container's locals, and we do get a collision
32170                     // conflict.
32171                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32172             }
32173             return 0 /* None */;
32174         }
32175         function addToContainerChain(next) {
32176             if (lastContainer) {
32177                 lastContainer.nextContainer = next;
32178             }
32179             lastContainer = next;
32180         }
32181         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32182             switch (container.kind) {
32183                 // Modules, source files, and classes need specialized handling for how their
32184                 // members are declared (for example, a member of a class will go into a specific
32185                 // symbol table depending on if it is static or not). We defer to specialized
32186                 // handlers to take care of declaring these child members.
32187                 case 249 /* ModuleDeclaration */:
32188                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32189                 case 290 /* SourceFile */:
32190                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32191                 case 214 /* ClassExpression */:
32192                 case 245 /* ClassDeclaration */:
32193                     return declareClassMember(node, symbolFlags, symbolExcludes);
32194                 case 248 /* EnumDeclaration */:
32195                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32196                 case 173 /* TypeLiteral */:
32197                 case 304 /* JSDocTypeLiteral */:
32198                 case 193 /* ObjectLiteralExpression */:
32199                 case 246 /* InterfaceDeclaration */:
32200                 case 274 /* JsxAttributes */:
32201                     // Interface/Object-types always have their children added to the 'members' of
32202                     // their container. They are only accessible through an instance of their
32203                     // container, and are never in scope otherwise (even inside the body of the
32204                     // object / type / interface declaring them). An exception is type parameters,
32205                     // which are in scope without qualification (similar to 'locals').
32206                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32207                 case 170 /* FunctionType */:
32208                 case 171 /* ConstructorType */:
32209                 case 165 /* CallSignature */:
32210                 case 166 /* ConstructSignature */:
32211                 case 305 /* JSDocSignature */:
32212                 case 167 /* IndexSignature */:
32213                 case 161 /* MethodDeclaration */:
32214                 case 160 /* MethodSignature */:
32215                 case 162 /* Constructor */:
32216                 case 163 /* GetAccessor */:
32217                 case 164 /* SetAccessor */:
32218                 case 244 /* FunctionDeclaration */:
32219                 case 201 /* FunctionExpression */:
32220                 case 202 /* ArrowFunction */:
32221                 case 300 /* JSDocFunctionType */:
32222                 case 322 /* JSDocTypedefTag */:
32223                 case 315 /* JSDocCallbackTag */:
32224                 case 247 /* TypeAliasDeclaration */:
32225                 case 186 /* MappedType */:
32226                     // All the children of these container types are never visible through another
32227                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32228                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32229                     // their container in the tree). To accomplish this, we simply add their declared
32230                     // symbol to the 'locals' of the container.  These symbols can then be found as
32231                     // the type checker walks up the containers, checking them for matching names.
32232                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32233             }
32234         }
32235         function declareClassMember(node, symbolFlags, symbolExcludes) {
32236             return ts.hasModifier(node, 32 /* Static */)
32237                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32238                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32239         }
32240         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32241             return ts.isExternalModule(file)
32242                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32243                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32244         }
32245         function hasExportDeclarations(node) {
32246             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32247             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32248         }
32249         function setExportContextFlag(node) {
32250             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32251             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32252             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32253                 node.flags |= 64 /* ExportContext */;
32254             }
32255             else {
32256                 node.flags &= ~64 /* ExportContext */;
32257             }
32258         }
32259         function bindModuleDeclaration(node) {
32260             setExportContextFlag(node);
32261             if (ts.isAmbientModule(node)) {
32262                 if (ts.hasModifier(node, 1 /* Export */)) {
32263                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32264                 }
32265                 if (ts.isModuleAugmentationExternal(node)) {
32266                     declareModuleSymbol(node);
32267                 }
32268                 else {
32269                     var pattern = void 0;
32270                     if (node.name.kind === 10 /* StringLiteral */) {
32271                         var text = node.name.text;
32272                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32273                             pattern = ts.tryParsePattern(text);
32274                         }
32275                         else {
32276                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32277                         }
32278                     }
32279                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32280                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32281                 }
32282             }
32283             else {
32284                 var state = declareModuleSymbol(node);
32285                 if (state !== 0 /* NonInstantiated */) {
32286                     var symbol = node.symbol;
32287                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32288                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32289                         // Current must be `const enum` only
32290                         && state === 2 /* ConstEnumOnly */
32291                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32292                         && symbol.constEnumOnlyModule !== false;
32293                 }
32294             }
32295         }
32296         function declareModuleSymbol(node) {
32297             var state = getModuleInstanceState(node);
32298             var instantiated = state !== 0 /* NonInstantiated */;
32299             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32300             return state;
32301         }
32302         function bindFunctionOrConstructorType(node) {
32303             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32304             // to the one we would get for: { <...>(...): T }
32305             //
32306             // We do that by making an anonymous type literal symbol, and then setting the function
32307             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32308             // from an actual type literal symbol you would have gotten had you used the long form.
32309             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32310             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32311             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32312             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32313             typeLiteralSymbol.members = ts.createSymbolTable();
32314             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32315         }
32316         function bindObjectLiteralExpression(node) {
32317             var ElementKind;
32318             (function (ElementKind) {
32319                 ElementKind[ElementKind["Property"] = 1] = "Property";
32320                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32321             })(ElementKind || (ElementKind = {}));
32322             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32323                 var seen = ts.createUnderscoreEscapedMap();
32324                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32325                     var prop = _a[_i];
32326                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32327                         continue;
32328                     }
32329                     var identifier = prop.name;
32330                     // ECMA-262 11.1.5 Object Initializer
32331                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32332                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32333                     // IsDataDescriptor(propId.descriptor) is true.
32334                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32335                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32336                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32337                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32338                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32339                         ? 1 /* Property */
32340                         : 2 /* Accessor */;
32341                     var existingKind = seen.get(identifier.escapedText);
32342                     if (!existingKind) {
32343                         seen.set(identifier.escapedText, currentKind);
32344                         continue;
32345                     }
32346                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32347                         var span = ts.getErrorSpanForNode(file, identifier);
32348                         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));
32349                     }
32350                 }
32351             }
32352             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32353         }
32354         function bindJsxAttributes(node) {
32355             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32356         }
32357         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32358             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32359         }
32360         function bindAnonymousDeclaration(node, symbolFlags, name) {
32361             var symbol = createSymbol(symbolFlags, name);
32362             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32363                 symbol.parent = container.symbol;
32364             }
32365             addDeclarationToSymbol(symbol, node, symbolFlags);
32366             return symbol;
32367         }
32368         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32369             switch (blockScopeContainer.kind) {
32370                 case 249 /* ModuleDeclaration */:
32371                     declareModuleMember(node, symbolFlags, symbolExcludes);
32372                     break;
32373                 case 290 /* SourceFile */:
32374                     if (ts.isExternalOrCommonJsModule(container)) {
32375                         declareModuleMember(node, symbolFlags, symbolExcludes);
32376                         break;
32377                     }
32378                 // falls through
32379                 default:
32380                     if (!blockScopeContainer.locals) {
32381                         blockScopeContainer.locals = ts.createSymbolTable();
32382                         addToContainerChain(blockScopeContainer);
32383                     }
32384                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32385             }
32386         }
32387         function delayedBindJSDocTypedefTag() {
32388             if (!delayedTypeAliases) {
32389                 return;
32390             }
32391             var saveContainer = container;
32392             var saveLastContainer = lastContainer;
32393             var saveBlockScopeContainer = blockScopeContainer;
32394             var saveParent = parent;
32395             var saveCurrentFlow = currentFlow;
32396             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32397                 var typeAlias = delayedTypeAliases_1[_i];
32398                 var host = ts.getJSDocHost(typeAlias);
32399                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32400                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32401                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32402                 parent = typeAlias;
32403                 bind(typeAlias.typeExpression);
32404                 var declName = ts.getNameOfDeclaration(typeAlias);
32405                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32406                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32407                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32408                     if (isTopLevel) {
32409                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32410                         var oldContainer = container;
32411                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32412                             case 1 /* ExportsProperty */:
32413                             case 2 /* ModuleExports */:
32414                                 if (!ts.isExternalOrCommonJsModule(file)) {
32415                                     container = undefined;
32416                                 }
32417                                 else {
32418                                     container = file;
32419                                 }
32420                                 break;
32421                             case 4 /* ThisProperty */:
32422                                 container = declName.parent.expression;
32423                                 break;
32424                             case 3 /* PrototypeProperty */:
32425                                 container = declName.parent.expression.name;
32426                                 break;
32427                             case 5 /* Property */:
32428                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32429                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32430                                         : declName.parent.expression;
32431                                 break;
32432                             case 0 /* None */:
32433                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32434                         }
32435                         if (container) {
32436                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32437                         }
32438                         container = oldContainer;
32439                     }
32440                 }
32441                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32442                     parent = typeAlias.parent;
32443                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32444                 }
32445                 else {
32446                     bind(typeAlias.fullName);
32447                 }
32448             }
32449             container = saveContainer;
32450             lastContainer = saveLastContainer;
32451             blockScopeContainer = saveBlockScopeContainer;
32452             parent = saveParent;
32453             currentFlow = saveCurrentFlow;
32454         }
32455         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32456         // check for reserved words used as identifiers in strict mode code.
32457         function checkStrictModeIdentifier(node) {
32458             if (inStrictMode &&
32459                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32460                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32461                 !ts.isIdentifierName(node) &&
32462                 !(node.flags & 8388608 /* Ambient */) &&
32463                 !(node.flags & 4194304 /* JSDoc */)) {
32464                 // Report error only if there are no parse errors in file
32465                 if (!file.parseDiagnostics.length) {
32466                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32467                 }
32468             }
32469         }
32470         function getStrictModeIdentifierMessage(node) {
32471             // Provide specialized messages to help the user understand why we think they're in
32472             // strict mode.
32473             if (ts.getContainingClass(node)) {
32474                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32475             }
32476             if (file.externalModuleIndicator) {
32477                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32478             }
32479             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32480         }
32481         // The binder visits every node, so this is a good place to check for
32482         // the reserved private name (there is only one)
32483         function checkPrivateIdentifier(node) {
32484             if (node.escapedText === "#constructor") {
32485                 // Report error only if there are no parse errors in file
32486                 if (!file.parseDiagnostics.length) {
32487                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32488                 }
32489             }
32490         }
32491         function checkStrictModeBinaryExpression(node) {
32492             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32493                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32494                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32495                 checkStrictModeEvalOrArguments(node, node.left);
32496             }
32497         }
32498         function checkStrictModeCatchClause(node) {
32499             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32500             // Catch production is eval or arguments
32501             if (inStrictMode && node.variableDeclaration) {
32502                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32503             }
32504         }
32505         function checkStrictModeDeleteExpression(node) {
32506             // Grammar checking
32507             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32508                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32509                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32510                 var span = ts.getErrorSpanForNode(file, node.expression);
32511                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32512             }
32513         }
32514         function isEvalOrArgumentsIdentifier(node) {
32515             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32516         }
32517         function checkStrictModeEvalOrArguments(contextNode, name) {
32518             if (name && name.kind === 75 /* Identifier */) {
32519                 var identifier = name;
32520                 if (isEvalOrArgumentsIdentifier(identifier)) {
32521                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32522                     // otherwise report generic error message.
32523                     var span = ts.getErrorSpanForNode(file, name);
32524                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32525                 }
32526             }
32527         }
32528         function getStrictModeEvalOrArgumentsMessage(node) {
32529             // Provide specialized messages to help the user understand why we think they're in
32530             // strict mode.
32531             if (ts.getContainingClass(node)) {
32532                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32533             }
32534             if (file.externalModuleIndicator) {
32535                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32536             }
32537             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32538         }
32539         function checkStrictModeFunctionName(node) {
32540             if (inStrictMode) {
32541                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32542                 checkStrictModeEvalOrArguments(node, node.name);
32543             }
32544         }
32545         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32546             // Provide specialized messages to help the user understand why we think they're in
32547             // strict mode.
32548             if (ts.getContainingClass(node)) {
32549                 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;
32550             }
32551             if (file.externalModuleIndicator) {
32552                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32553             }
32554             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32555         }
32556         function checkStrictModeFunctionDeclaration(node) {
32557             if (languageVersion < 2 /* ES2015 */) {
32558                 // Report error if function is not top level function declaration
32559                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32560                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32561                     !ts.isFunctionLike(blockScopeContainer)) {
32562                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32563                     // otherwise report generic error message.
32564                     var errorSpan = ts.getErrorSpanForNode(file, node);
32565                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32566                 }
32567             }
32568         }
32569         function checkStrictModeNumericLiteral(node) {
32570             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32571                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32572             }
32573         }
32574         function checkStrictModePostfixUnaryExpression(node) {
32575             // Grammar checking
32576             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32577             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32578             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32579             if (inStrictMode) {
32580                 checkStrictModeEvalOrArguments(node, node.operand);
32581             }
32582         }
32583         function checkStrictModePrefixUnaryExpression(node) {
32584             // Grammar checking
32585             if (inStrictMode) {
32586                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32587                     checkStrictModeEvalOrArguments(node, node.operand);
32588                 }
32589             }
32590         }
32591         function checkStrictModeWithStatement(node) {
32592             // Grammar checking for withStatement
32593             if (inStrictMode) {
32594                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32595             }
32596         }
32597         function checkStrictModeLabeledStatement(node) {
32598             // Grammar checking for labeledStatement
32599             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32600                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32601                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32602                 }
32603             }
32604         }
32605         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32606             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32607             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32608         }
32609         function errorOrSuggestionOnNode(isError, node, message) {
32610             errorOrSuggestionOnRange(isError, node, node, message);
32611         }
32612         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32613             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32614         }
32615         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32616             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32617             if (isError) {
32618                 file.bindDiagnostics.push(diag);
32619             }
32620             else {
32621                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32622             }
32623         }
32624         function bind(node) {
32625             if (!node) {
32626                 return;
32627             }
32628             node.parent = parent;
32629             var saveInStrictMode = inStrictMode;
32630             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32631             // its symbol might be in the same scope with the current node's symbol. Consider:
32632             //
32633             //     /** @typedef {string | number} MyType */
32634             //     function foo();
32635             //
32636             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32637             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32638             // and skip binding this tag later when binding all the other jsdoc tags.
32639             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32640             // and then potentially add the symbol to an appropriate symbol table. Possible
32641             // destination symbol tables are:
32642             //
32643             //  1) The 'exports' table of the current container's symbol.
32644             //  2) The 'members' table of the current container's symbol.
32645             //  3) The 'locals' table of the current container.
32646             //
32647             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32648             // (like TypeLiterals for example) will not be put in any table.
32649             bindWorker(node);
32650             // Then we recurse into the children of the node to bind them as well. For certain
32651             // symbols we do specialized work when we recurse. For example, we'll keep track of
32652             // the current 'container' node when it changes. This helps us know which symbol table
32653             // a local should go into for example. Since terminal nodes are known not to have
32654             // children, as an optimization we don't process those.
32655             if (node.kind > 152 /* LastToken */) {
32656                 var saveParent = parent;
32657                 parent = node;
32658                 var containerFlags = getContainerFlags(node);
32659                 if (containerFlags === 0 /* None */) {
32660                     bindChildren(node);
32661                 }
32662                 else {
32663                     bindContainer(node, containerFlags);
32664                 }
32665                 parent = saveParent;
32666             }
32667             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32668                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32669                 var saveParent = parent;
32670                 if (node.kind === 1 /* EndOfFileToken */)
32671                     parent = node;
32672                 bindJSDoc(node);
32673                 parent = saveParent;
32674             }
32675             inStrictMode = saveInStrictMode;
32676         }
32677         function bindJSDoc(node) {
32678             if (ts.hasJSDocNodes(node)) {
32679                 if (ts.isInJSFile(node)) {
32680                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32681                         var j = _a[_i];
32682                         bind(j);
32683                     }
32684                 }
32685                 else {
32686                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32687                         var j = _c[_b];
32688                         setParentPointers(node, j);
32689                     }
32690                 }
32691             }
32692         }
32693         function updateStrictModeStatementList(statements) {
32694             if (!inStrictMode) {
32695                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32696                     var statement = statements_2[_i];
32697                     if (!ts.isPrologueDirective(statement)) {
32698                         return;
32699                     }
32700                     if (isUseStrictPrologueDirective(statement)) {
32701                         inStrictMode = true;
32702                         return;
32703                     }
32704                 }
32705             }
32706         }
32707         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32708         function isUseStrictPrologueDirective(node) {
32709             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32710             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32711             // string to contain unicode escapes (as per ES5).
32712             return nodeText === '"use strict"' || nodeText === "'use strict'";
32713         }
32714         function bindWorker(node) {
32715             switch (node.kind) {
32716                 /* Strict mode checks */
32717                 case 75 /* Identifier */:
32718                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32719                     // because it requires all containing namespaces to be in effect, namely the
32720                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32721                     if (node.isInJSDocNamespace) {
32722                         var parentNode = node.parent;
32723                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32724                             parentNode = parentNode.parent;
32725                         }
32726                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32727                         break;
32728                     }
32729                 // falls through
32730                 case 104 /* ThisKeyword */:
32731                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32732                         node.flowNode = currentFlow;
32733                     }
32734                     return checkStrictModeIdentifier(node);
32735                 case 76 /* PrivateIdentifier */:
32736                     return checkPrivateIdentifier(node);
32737                 case 194 /* PropertyAccessExpression */:
32738                 case 195 /* ElementAccessExpression */:
32739                     var expr = node;
32740                     if (currentFlow && isNarrowableReference(expr)) {
32741                         expr.flowNode = currentFlow;
32742                     }
32743                     if (ts.isSpecialPropertyDeclaration(expr)) {
32744                         bindSpecialPropertyDeclaration(expr);
32745                     }
32746                     if (ts.isInJSFile(expr) &&
32747                         file.commonJsModuleIndicator &&
32748                         ts.isModuleExportsAccessExpression(expr) &&
32749                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32750                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32751                     }
32752                     break;
32753                 case 209 /* BinaryExpression */:
32754                     var specialKind = ts.getAssignmentDeclarationKind(node);
32755                     switch (specialKind) {
32756                         case 1 /* ExportsProperty */:
32757                             bindExportsPropertyAssignment(node);
32758                             break;
32759                         case 2 /* ModuleExports */:
32760                             bindModuleExportsAssignment(node);
32761                             break;
32762                         case 3 /* PrototypeProperty */:
32763                             bindPrototypePropertyAssignment(node.left, node);
32764                             break;
32765                         case 6 /* Prototype */:
32766                             bindPrototypeAssignment(node);
32767                             break;
32768                         case 4 /* ThisProperty */:
32769                             bindThisPropertyAssignment(node);
32770                             break;
32771                         case 5 /* Property */:
32772                             bindSpecialPropertyAssignment(node);
32773                             break;
32774                         case 0 /* None */:
32775                             // Nothing to do
32776                             break;
32777                         default:
32778                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32779                     }
32780                     return checkStrictModeBinaryExpression(node);
32781                 case 280 /* CatchClause */:
32782                     return checkStrictModeCatchClause(node);
32783                 case 203 /* DeleteExpression */:
32784                     return checkStrictModeDeleteExpression(node);
32785                 case 8 /* NumericLiteral */:
32786                     return checkStrictModeNumericLiteral(node);
32787                 case 208 /* PostfixUnaryExpression */:
32788                     return checkStrictModePostfixUnaryExpression(node);
32789                 case 207 /* PrefixUnaryExpression */:
32790                     return checkStrictModePrefixUnaryExpression(node);
32791                 case 236 /* WithStatement */:
32792                     return checkStrictModeWithStatement(node);
32793                 case 238 /* LabeledStatement */:
32794                     return checkStrictModeLabeledStatement(node);
32795                 case 183 /* ThisType */:
32796                     seenThisKeyword = true;
32797                     return;
32798                 case 168 /* TypePredicate */:
32799                     break; // Binding the children will handle everything
32800                 case 155 /* TypeParameter */:
32801                     return bindTypeParameter(node);
32802                 case 156 /* Parameter */:
32803                     return bindParameter(node);
32804                 case 242 /* VariableDeclaration */:
32805                     return bindVariableDeclarationOrBindingElement(node);
32806                 case 191 /* BindingElement */:
32807                     node.flowNode = currentFlow;
32808                     return bindVariableDeclarationOrBindingElement(node);
32809                 case 159 /* PropertyDeclaration */:
32810                 case 158 /* PropertySignature */:
32811                     return bindPropertyWorker(node);
32812                 case 281 /* PropertyAssignment */:
32813                 case 282 /* ShorthandPropertyAssignment */:
32814                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32815                 case 284 /* EnumMember */:
32816                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32817                 case 165 /* CallSignature */:
32818                 case 166 /* ConstructSignature */:
32819                 case 167 /* IndexSignature */:
32820                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32821                 case 161 /* MethodDeclaration */:
32822                 case 160 /* MethodSignature */:
32823                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32824                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32825                     // so that it will conflict with any other object literal members with the same
32826                     // name.
32827                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32828                 case 244 /* FunctionDeclaration */:
32829                     return bindFunctionDeclaration(node);
32830                 case 162 /* Constructor */:
32831                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32832                 case 163 /* GetAccessor */:
32833                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32834                 case 164 /* SetAccessor */:
32835                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32836                 case 170 /* FunctionType */:
32837                 case 300 /* JSDocFunctionType */:
32838                 case 305 /* JSDocSignature */:
32839                 case 171 /* ConstructorType */:
32840                     return bindFunctionOrConstructorType(node);
32841                 case 173 /* TypeLiteral */:
32842                 case 304 /* JSDocTypeLiteral */:
32843                 case 186 /* MappedType */:
32844                     return bindAnonymousTypeWorker(node);
32845                 case 310 /* JSDocClassTag */:
32846                     return bindJSDocClassTag(node);
32847                 case 193 /* ObjectLiteralExpression */:
32848                     return bindObjectLiteralExpression(node);
32849                 case 201 /* FunctionExpression */:
32850                 case 202 /* ArrowFunction */:
32851                     return bindFunctionExpression(node);
32852                 case 196 /* CallExpression */:
32853                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
32854                     switch (assignmentKind) {
32855                         case 7 /* ObjectDefinePropertyValue */:
32856                             return bindObjectDefinePropertyAssignment(node);
32857                         case 8 /* ObjectDefinePropertyExports */:
32858                             return bindObjectDefinePropertyExport(node);
32859                         case 9 /* ObjectDefinePrototypeProperty */:
32860                             return bindObjectDefinePrototypeProperty(node);
32861                         case 0 /* None */:
32862                             break; // Nothing to do
32863                         default:
32864                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
32865                     }
32866                     if (ts.isInJSFile(node)) {
32867                         bindCallExpression(node);
32868                     }
32869                     break;
32870                 // Members of classes, interfaces, and modules
32871                 case 214 /* ClassExpression */:
32872                 case 245 /* ClassDeclaration */:
32873                     // All classes are automatically in strict mode in ES6.
32874                     inStrictMode = true;
32875                     return bindClassLikeDeclaration(node);
32876                 case 246 /* InterfaceDeclaration */:
32877                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
32878                 case 247 /* TypeAliasDeclaration */:
32879                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32880                 case 248 /* EnumDeclaration */:
32881                     return bindEnumDeclaration(node);
32882                 case 249 /* ModuleDeclaration */:
32883                     return bindModuleDeclaration(node);
32884                 // Jsx-attributes
32885                 case 274 /* JsxAttributes */:
32886                     return bindJsxAttributes(node);
32887                 case 273 /* JsxAttribute */:
32888                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
32889                 // Imports and exports
32890                 case 253 /* ImportEqualsDeclaration */:
32891                 case 256 /* NamespaceImport */:
32892                 case 258 /* ImportSpecifier */:
32893                 case 263 /* ExportSpecifier */:
32894                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32895                 case 252 /* NamespaceExportDeclaration */:
32896                     return bindNamespaceExportDeclaration(node);
32897                 case 255 /* ImportClause */:
32898                     return bindImportClause(node);
32899                 case 260 /* ExportDeclaration */:
32900                     return bindExportDeclaration(node);
32901                 case 259 /* ExportAssignment */:
32902                     return bindExportAssignment(node);
32903                 case 290 /* SourceFile */:
32904                     updateStrictModeStatementList(node.statements);
32905                     return bindSourceFileIfExternalModule();
32906                 case 223 /* Block */:
32907                     if (!ts.isFunctionLike(node.parent)) {
32908                         return;
32909                     }
32910                 // falls through
32911                 case 250 /* ModuleBlock */:
32912                     return updateStrictModeStatementList(node.statements);
32913                 case 317 /* JSDocParameterTag */:
32914                     if (node.parent.kind === 305 /* JSDocSignature */) {
32915                         return bindParameter(node);
32916                     }
32917                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
32918                         break;
32919                     }
32920                 // falls through
32921                 case 323 /* JSDocPropertyTag */:
32922                     var propTag = node;
32923                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
32924                         4 /* Property */ | 16777216 /* Optional */ :
32925                         4 /* Property */;
32926                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
32927                 case 322 /* JSDocTypedefTag */:
32928                 case 315 /* JSDocCallbackTag */:
32929                 case 316 /* JSDocEnumTag */:
32930                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
32931             }
32932         }
32933         function bindPropertyWorker(node) {
32934             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
32935         }
32936         function bindAnonymousTypeWorker(node) {
32937             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
32938         }
32939         function bindSourceFileIfExternalModule() {
32940             setExportContextFlag(file);
32941             if (ts.isExternalModule(file)) {
32942                 bindSourceFileAsExternalModule();
32943             }
32944             else if (ts.isJsonSourceFile(file)) {
32945                 bindSourceFileAsExternalModule();
32946                 // Create symbol equivalent for the module.exports = {}
32947                 var originalSymbol = file.symbol;
32948                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
32949                 file.symbol = originalSymbol;
32950             }
32951         }
32952         function bindSourceFileAsExternalModule() {
32953             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
32954         }
32955         function bindExportAssignment(node) {
32956             if (!container.symbol || !container.symbol.exports) {
32957                 // Export assignment in some sort of block construct
32958                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
32959             }
32960             else {
32961                 var flags = ts.exportAssignmentIsAlias(node)
32962                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
32963                     ? 2097152 /* Alias */
32964                     // An export default clause with any other expression exports a value
32965                     : 4 /* Property */;
32966                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
32967                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
32968                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
32969                 if (node.isExportEquals) {
32970                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
32971                     ts.setValueDeclaration(symbol, node);
32972                 }
32973             }
32974         }
32975         function bindNamespaceExportDeclaration(node) {
32976             if (node.modifiers && node.modifiers.length) {
32977                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
32978             }
32979             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
32980                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
32981                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
32982                         : undefined;
32983             if (diag) {
32984                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
32985             }
32986             else {
32987                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
32988                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32989             }
32990         }
32991         function bindExportDeclaration(node) {
32992             if (!container.symbol || !container.symbol.exports) {
32993                 // Export * in some sort of block construct
32994                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
32995             }
32996             else if (!node.exportClause) {
32997                 // All export * declarations are collected in an __export symbol
32998                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
32999             }
33000             else if (ts.isNamespaceExport(node.exportClause)) {
33001                 // declareSymbol walks up parents to find name text, parent _must_ be set
33002                 // but won't be set by the normal binder walk until `bindChildren` later on.
33003                 node.exportClause.parent = node;
33004                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33005             }
33006         }
33007         function bindImportClause(node) {
33008             if (node.name) {
33009                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33010             }
33011         }
33012         function setCommonJsModuleIndicator(node) {
33013             if (file.externalModuleIndicator) {
33014                 return false;
33015             }
33016             if (!file.commonJsModuleIndicator) {
33017                 file.commonJsModuleIndicator = node;
33018                 bindSourceFileAsExternalModule();
33019             }
33020             return true;
33021         }
33022         function bindObjectDefinePropertyExport(node) {
33023             if (!setCommonJsModuleIndicator(node)) {
33024                 return;
33025             }
33026             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33027                 if (symbol) {
33028                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33029                 }
33030                 return symbol;
33031             });
33032             if (symbol) {
33033                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33034                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33035             }
33036         }
33037         function bindExportsPropertyAssignment(node) {
33038             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33039             // expression is the declaration
33040             if (!setCommonJsModuleIndicator(node)) {
33041                 return;
33042             }
33043             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33044                 if (symbol) {
33045                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33046                 }
33047                 return symbol;
33048             });
33049             if (symbol) {
33050                 var flags = ts.isClassExpression(node.right) ?
33051                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33052                     4 /* Property */ | 1048576 /* ExportValue */;
33053                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33054             }
33055         }
33056         function bindModuleExportsAssignment(node) {
33057             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33058             // is still pointing to 'module.exports'.
33059             // We do not want to consider this as 'export=' since a module can have only one of these.
33060             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33061             if (!setCommonJsModuleIndicator(node)) {
33062                 return;
33063             }
33064             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33065             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33066                 return;
33067             }
33068             // 'module.exports = expr' assignment
33069             var flags = ts.exportAssignmentIsAlias(node)
33070                 ? 2097152 /* Alias */
33071                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33072             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33073             ts.setValueDeclaration(symbol, node);
33074         }
33075         function bindThisPropertyAssignment(node) {
33076             ts.Debug.assert(ts.isInJSFile(node));
33077             // private identifiers *must* be declared (even in JS files)
33078             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33079                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33080             if (hasPrivateIdentifier) {
33081                 return;
33082             }
33083             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33084             switch (thisContainer.kind) {
33085                 case 244 /* FunctionDeclaration */:
33086                 case 201 /* FunctionExpression */:
33087                     var constructorSymbol = thisContainer.symbol;
33088                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33089                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33090                         var l = thisContainer.parent.left;
33091                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33092                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33093                         }
33094                     }
33095                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33096                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33097                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33098                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33099                         if (ts.hasDynamicName(node)) {
33100                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33101                         }
33102                         else {
33103                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33104                         }
33105                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33106                     }
33107                     break;
33108                 case 162 /* Constructor */:
33109                 case 159 /* PropertyDeclaration */:
33110                 case 161 /* MethodDeclaration */:
33111                 case 163 /* GetAccessor */:
33112                 case 164 /* SetAccessor */:
33113                     // this.foo assignment in a JavaScript class
33114                     // Bind this property to the containing class
33115                     var containingClass = thisContainer.parent;
33116                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33117                     if (ts.hasDynamicName(node)) {
33118                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33119                     }
33120                     else {
33121                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33122                     }
33123                     break;
33124                 case 290 /* SourceFile */:
33125                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33126                     if (ts.hasDynamicName(node)) {
33127                         break;
33128                     }
33129                     else if (thisContainer.commonJsModuleIndicator) {
33130                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33131                     }
33132                     else {
33133                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33134                     }
33135                     break;
33136                 default:
33137                     ts.Debug.failBadSyntaxKind(thisContainer);
33138             }
33139         }
33140         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33141             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33142             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33143         }
33144         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33145             if (symbol) {
33146                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33147                 members.set("" + ts.getNodeId(node), node);
33148             }
33149         }
33150         function bindSpecialPropertyDeclaration(node) {
33151             if (node.expression.kind === 104 /* ThisKeyword */) {
33152                 bindThisPropertyAssignment(node);
33153             }
33154             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33155                 if (ts.isPrototypeAccess(node.expression)) {
33156                     bindPrototypePropertyAssignment(node, node.parent);
33157                 }
33158                 else {
33159                     bindStaticPropertyAssignment(node);
33160                 }
33161             }
33162         }
33163         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33164         function bindPrototypeAssignment(node) {
33165             node.left.parent = node;
33166             node.right.parent = node;
33167             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33168         }
33169         function bindObjectDefinePrototypeProperty(node) {
33170             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33171             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33172                 // Ensure the namespace symbol becomes class-like
33173                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33174             }
33175             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33176         }
33177         /**
33178          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33179          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33180          */
33181         function bindPrototypePropertyAssignment(lhs, parent) {
33182             // Look up the function in the local scope, since prototype assignments should
33183             // follow the function declaration
33184             var classPrototype = lhs.expression;
33185             var constructorFunction = classPrototype.expression;
33186             // Fix up parent pointers since we're going to use these nodes before we bind into them
33187             lhs.parent = parent;
33188             constructorFunction.parent = classPrototype;
33189             classPrototype.parent = lhs;
33190             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33191         }
33192         function bindObjectDefinePropertyAssignment(node) {
33193             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33194             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33195             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33196             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33197         }
33198         function bindSpecialPropertyAssignment(node) {
33199             // Class declarations in Typescript do not allow property declarations
33200             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33201             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33202                 return;
33203             }
33204             // Fix up parent pointers since we're going to use these nodes before we bind into them
33205             node.left.parent = node;
33206             node.right.parent = node;
33207             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33208                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33209                 //    var util = module.exports;
33210                 //    util.property = function ...
33211                 bindExportsPropertyAssignment(node);
33212             }
33213             else if (ts.hasDynamicName(node)) {
33214                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33215                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33216                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33217             }
33218             else {
33219                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33220             }
33221         }
33222         /**
33223          * 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.
33224          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33225          */
33226         function bindStaticPropertyAssignment(node) {
33227             ts.Debug.assert(!ts.isIdentifier(node));
33228             node.expression.parent = node;
33229             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33230         }
33231         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33232             if (isToplevel && !isPrototypeProperty) {
33233                 // make symbols or add declarations for intermediate containers
33234                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33235                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33236                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33237                     if (symbol) {
33238                         addDeclarationToSymbol(symbol, id, flags_1);
33239                         return symbol;
33240                     }
33241                     else {
33242                         var table = parent ? parent.exports :
33243                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33244                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33245                     }
33246                 });
33247             }
33248             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33249                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33250             }
33251             return namespaceSymbol;
33252         }
33253         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33254             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33255                 return;
33256             }
33257             // Set up the members collection if it doesn't exist already
33258             var symbolTable = isPrototypeProperty ?
33259                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33260                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33261             var includes = 0 /* None */;
33262             var excludes = 0 /* None */;
33263             // Method-like
33264             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33265                 includes = 8192 /* Method */;
33266                 excludes = 103359 /* MethodExcludes */;
33267             }
33268             // Maybe accessor-like
33269             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33270                 if (ts.some(declaration.arguments[2].properties, function (p) {
33271                     var id = ts.getNameOfDeclaration(p);
33272                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33273                 })) {
33274                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33275                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33276                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33277                     excludes |= 78783 /* SetAccessorExcludes */;
33278                 }
33279                 if (ts.some(declaration.arguments[2].properties, function (p) {
33280                     var id = ts.getNameOfDeclaration(p);
33281                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33282                 })) {
33283                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33284                     excludes |= 46015 /* GetAccessorExcludes */;
33285                 }
33286             }
33287             if (includes === 0 /* None */) {
33288                 includes = 4 /* Property */;
33289                 excludes = 0 /* PropertyExcludes */;
33290             }
33291             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33292         }
33293         function isTopLevelNamespaceAssignment(propertyAccess) {
33294             return ts.isBinaryExpression(propertyAccess.parent)
33295                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33296                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33297         }
33298         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33299             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33300             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33301             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33302             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33303         }
33304         /**
33305          * Javascript expando values are:
33306          * - Functions
33307          * - classes
33308          * - namespaces
33309          * - variables initialized with function expressions
33310          * -                       with class expressions
33311          * -                       with empty object literals
33312          * -                       with non-empty object literals if assigned to the prototype property
33313          */
33314         function isExpandoSymbol(symbol) {
33315             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33316                 return true;
33317             }
33318             var node = symbol.valueDeclaration;
33319             if (node && ts.isCallExpression(node)) {
33320                 return !!ts.getAssignedExpandoInitializer(node);
33321             }
33322             var init = !node ? undefined :
33323                 ts.isVariableDeclaration(node) ? node.initializer :
33324                     ts.isBinaryExpression(node) ? node.right :
33325                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33326                             undefined;
33327             init = init && ts.getRightMostAssignedExpression(init);
33328             if (init) {
33329                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33330                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33331             }
33332             return false;
33333         }
33334         function getParentOfBinaryExpression(expr) {
33335             while (ts.isBinaryExpression(expr.parent)) {
33336                 expr = expr.parent;
33337             }
33338             return expr.parent;
33339         }
33340         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33341             if (lookupContainer === void 0) { lookupContainer = container; }
33342             if (ts.isIdentifier(node)) {
33343                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33344             }
33345             else {
33346                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33347                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33348             }
33349         }
33350         function forEachIdentifierInEntityName(e, parent, action) {
33351             if (isExportsOrModuleExportsOrAlias(file, e)) {
33352                 return file.symbol;
33353             }
33354             else if (ts.isIdentifier(e)) {
33355                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33356             }
33357             else {
33358                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33359                 var name = ts.getNameOrArgument(e);
33360                 // unreachable
33361                 if (ts.isPrivateIdentifier(name)) {
33362                     ts.Debug.fail("unexpected PrivateIdentifier");
33363                 }
33364                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33365             }
33366         }
33367         function bindCallExpression(node) {
33368             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33369             // this check if we've already seen the module indicator
33370             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33371                 setCommonJsModuleIndicator(node);
33372             }
33373         }
33374         function bindClassLikeDeclaration(node) {
33375             if (node.kind === 245 /* ClassDeclaration */) {
33376                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33377             }
33378             else {
33379                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33380                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33381                 // Add name of class expression into the map for semantic classifier
33382                 if (node.name) {
33383                     classifiableNames.set(node.name.escapedText, true);
33384                 }
33385             }
33386             var symbol = node.symbol;
33387             // TypeScript 1.0 spec (April 2014): 8.4
33388             // Every class automatically contains a static property member named 'prototype', the
33389             // type of which is an instantiation of the class type with type Any supplied as a type
33390             // argument for each type parameter. It is an error to explicitly declare a static
33391             // property member with the name 'prototype'.
33392             //
33393             // Note: we check for this here because this class may be merging into a module.  The
33394             // module might have an exported variable called 'prototype'.  We can't allow that as
33395             // that would clash with the built-in 'prototype' for the class.
33396             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33397             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33398             if (symbolExport) {
33399                 if (node.name) {
33400                     node.name.parent = node;
33401                 }
33402                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33403             }
33404             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33405             prototypeSymbol.parent = symbol;
33406         }
33407         function bindEnumDeclaration(node) {
33408             return ts.isEnumConst(node)
33409                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33410                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33411         }
33412         function bindVariableDeclarationOrBindingElement(node) {
33413             if (inStrictMode) {
33414                 checkStrictModeEvalOrArguments(node, node.name);
33415             }
33416             if (!ts.isBindingPattern(node.name)) {
33417                 if (ts.isBlockOrCatchScoped(node)) {
33418                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33419                 }
33420                 else if (ts.isParameterDeclaration(node)) {
33421                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33422                     // because its parent chain has already been set up, since parents are set before descending into children.
33423                     //
33424                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33425                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33426                     // For example:
33427                     //      function foo([a,a]) {} // Duplicate Identifier error
33428                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33429                     //                             // which correctly set excluded symbols
33430                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33431                 }
33432                 else {
33433                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33434                 }
33435             }
33436         }
33437         function bindParameter(node) {
33438             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33439                 return;
33440             }
33441             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33442                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33443                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33444                 checkStrictModeEvalOrArguments(node, node.name);
33445             }
33446             if (ts.isBindingPattern(node.name)) {
33447                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33448             }
33449             else {
33450                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33451             }
33452             // If this is a property-parameter, then also declare the property symbol into the
33453             // containing class.
33454             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33455                 var classDeclaration = node.parent.parent;
33456                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33457             }
33458         }
33459         function bindFunctionDeclaration(node) {
33460             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33461                 if (ts.isAsyncFunction(node)) {
33462                     emitFlags |= 2048 /* HasAsyncFunctions */;
33463                 }
33464             }
33465             checkStrictModeFunctionName(node);
33466             if (inStrictMode) {
33467                 checkStrictModeFunctionDeclaration(node);
33468                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33469             }
33470             else {
33471                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33472             }
33473         }
33474         function bindFunctionExpression(node) {
33475             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33476                 if (ts.isAsyncFunction(node)) {
33477                     emitFlags |= 2048 /* HasAsyncFunctions */;
33478                 }
33479             }
33480             if (currentFlow) {
33481                 node.flowNode = currentFlow;
33482             }
33483             checkStrictModeFunctionName(node);
33484             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33485             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33486         }
33487         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33488             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33489                 emitFlags |= 2048 /* HasAsyncFunctions */;
33490             }
33491             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33492                 node.flowNode = currentFlow;
33493             }
33494             return ts.hasDynamicName(node)
33495                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33496                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33497         }
33498         function getInferTypeContainer(node) {
33499             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33500             return extendsType && extendsType.parent;
33501         }
33502         function bindTypeParameter(node) {
33503             if (ts.isJSDocTemplateTag(node.parent)) {
33504                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33505                 if (container_1) {
33506                     if (!container_1.locals) {
33507                         container_1.locals = ts.createSymbolTable();
33508                     }
33509                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33510                 }
33511                 else {
33512                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33513                 }
33514             }
33515             else if (node.parent.kind === 181 /* InferType */) {
33516                 var container_2 = getInferTypeContainer(node.parent);
33517                 if (container_2) {
33518                     if (!container_2.locals) {
33519                         container_2.locals = ts.createSymbolTable();
33520                     }
33521                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33522                 }
33523                 else {
33524                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33525                 }
33526             }
33527             else {
33528                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33529             }
33530         }
33531         // reachability checks
33532         function shouldReportErrorOnModuleDeclaration(node) {
33533             var instanceState = getModuleInstanceState(node);
33534             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33535         }
33536         function checkUnreachable(node) {
33537             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33538                 return false;
33539             }
33540             if (currentFlow === unreachableFlow) {
33541                 var reportError = 
33542                 // report error on all statements except empty ones
33543                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33544                     // report error on class declarations
33545                     node.kind === 245 /* ClassDeclaration */ ||
33546                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33547                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33548                 if (reportError) {
33549                     currentFlow = reportedUnreachableFlow;
33550                     if (!options.allowUnreachableCode) {
33551                         // unreachable code is reported if
33552                         // - user has explicitly asked about it AND
33553                         // - statement is in not ambient context (statements in ambient context is already an error
33554                         //   so we should not report extras) AND
33555                         //   - node is not variable statement OR
33556                         //   - node is block scoped variable statement OR
33557                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33558                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33559                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33560                         var isError_1 = ts.unreachableCodeIsError(options) &&
33561                             !(node.flags & 8388608 /* Ambient */) &&
33562                             (!ts.isVariableStatement(node) ||
33563                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33564                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33565                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33566                     }
33567                 }
33568             }
33569             return true;
33570         }
33571     }
33572     function eachUnreachableRange(node, cb) {
33573         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33574             var statements = node.parent.statements;
33575             var slice_1 = ts.sliceAfter(statements, node);
33576             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33577         }
33578         else {
33579             cb(node, node);
33580         }
33581     }
33582     // As opposed to a pure declaration like an `interface`
33583     function isExecutableStatement(s) {
33584         // Don't remove statements that can validly be used before they appear.
33585         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33586             // `var x;` may declare a variable used above
33587             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33588     }
33589     function isPurelyTypeDeclaration(s) {
33590         switch (s.kind) {
33591             case 246 /* InterfaceDeclaration */:
33592             case 247 /* TypeAliasDeclaration */:
33593                 return true;
33594             case 249 /* ModuleDeclaration */:
33595                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33596             case 248 /* EnumDeclaration */:
33597                 return ts.hasModifier(s, 2048 /* Const */);
33598             default:
33599                 return false;
33600         }
33601     }
33602     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33603         var i = 0;
33604         var q = [node];
33605         while (q.length && i < 100) {
33606             i++;
33607             node = q.shift();
33608             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33609                 return true;
33610             }
33611             else if (ts.isIdentifier(node)) {
33612                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33613                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33614                     var init = symbol.valueDeclaration.initializer;
33615                     q.push(init);
33616                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33617                         q.push(init.left);
33618                         q.push(init.right);
33619                     }
33620                 }
33621             }
33622         }
33623         return false;
33624     }
33625     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33626     function lookupSymbolForNameWorker(container, name) {
33627         var local = container.locals && container.locals.get(name);
33628         if (local) {
33629             return local.exportSymbol || local;
33630         }
33631         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33632             return container.jsGlobalAugmentations.get(name);
33633         }
33634         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33635     }
33636     /**
33637      * Computes the transform flags for a node, given the transform flags of its subtree
33638      *
33639      * @param node The node to analyze
33640      * @param subtreeFlags Transform flags computed for this node's subtree
33641      */
33642     function computeTransformFlagsForNode(node, subtreeFlags) {
33643         var kind = node.kind;
33644         switch (kind) {
33645             case 196 /* CallExpression */:
33646                 return computeCallExpression(node, subtreeFlags);
33647             case 197 /* NewExpression */:
33648                 return computeNewExpression(node, subtreeFlags);
33649             case 249 /* ModuleDeclaration */:
33650                 return computeModuleDeclaration(node, subtreeFlags);
33651             case 200 /* ParenthesizedExpression */:
33652                 return computeParenthesizedExpression(node, subtreeFlags);
33653             case 209 /* BinaryExpression */:
33654                 return computeBinaryExpression(node, subtreeFlags);
33655             case 226 /* ExpressionStatement */:
33656                 return computeExpressionStatement(node, subtreeFlags);
33657             case 156 /* Parameter */:
33658                 return computeParameter(node, subtreeFlags);
33659             case 202 /* ArrowFunction */:
33660                 return computeArrowFunction(node, subtreeFlags);
33661             case 201 /* FunctionExpression */:
33662                 return computeFunctionExpression(node, subtreeFlags);
33663             case 244 /* FunctionDeclaration */:
33664                 return computeFunctionDeclaration(node, subtreeFlags);
33665             case 242 /* VariableDeclaration */:
33666                 return computeVariableDeclaration(node, subtreeFlags);
33667             case 243 /* VariableDeclarationList */:
33668                 return computeVariableDeclarationList(node, subtreeFlags);
33669             case 225 /* VariableStatement */:
33670                 return computeVariableStatement(node, subtreeFlags);
33671             case 238 /* LabeledStatement */:
33672                 return computeLabeledStatement(node, subtreeFlags);
33673             case 245 /* ClassDeclaration */:
33674                 return computeClassDeclaration(node, subtreeFlags);
33675             case 214 /* ClassExpression */:
33676                 return computeClassExpression(node, subtreeFlags);
33677             case 279 /* HeritageClause */:
33678                 return computeHeritageClause(node, subtreeFlags);
33679             case 280 /* CatchClause */:
33680                 return computeCatchClause(node, subtreeFlags);
33681             case 216 /* ExpressionWithTypeArguments */:
33682                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33683             case 162 /* Constructor */:
33684                 return computeConstructor(node, subtreeFlags);
33685             case 159 /* PropertyDeclaration */:
33686                 return computePropertyDeclaration(node, subtreeFlags);
33687             case 161 /* MethodDeclaration */:
33688                 return computeMethod(node, subtreeFlags);
33689             case 163 /* GetAccessor */:
33690             case 164 /* SetAccessor */:
33691                 return computeAccessor(node, subtreeFlags);
33692             case 253 /* ImportEqualsDeclaration */:
33693                 return computeImportEquals(node, subtreeFlags);
33694             case 194 /* PropertyAccessExpression */:
33695                 return computePropertyAccess(node, subtreeFlags);
33696             case 195 /* ElementAccessExpression */:
33697                 return computeElementAccess(node, subtreeFlags);
33698             case 267 /* JsxSelfClosingElement */:
33699             case 268 /* JsxOpeningElement */:
33700                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33701             default:
33702                 return computeOther(node, kind, subtreeFlags);
33703         }
33704     }
33705     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33706     function computeCallExpression(node, subtreeFlags) {
33707         var transformFlags = subtreeFlags;
33708         var callee = ts.skipOuterExpressions(node.expression);
33709         var expression = node.expression;
33710         if (node.flags & 32 /* OptionalChain */) {
33711             transformFlags |= 8 /* ContainsES2020 */;
33712         }
33713         if (node.typeArguments) {
33714             transformFlags |= 1 /* AssertTypeScript */;
33715         }
33716         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33717             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33718             // node.
33719             transformFlags |= 256 /* AssertES2015 */;
33720             if (ts.isSuperProperty(callee)) {
33721                 transformFlags |= 4096 /* ContainsLexicalThis */;
33722             }
33723         }
33724         if (expression.kind === 96 /* ImportKeyword */) {
33725             transformFlags |= 2097152 /* ContainsDynamicImport */;
33726         }
33727         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33728         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33729     }
33730     function computeNewExpression(node, subtreeFlags) {
33731         var transformFlags = subtreeFlags;
33732         if (node.typeArguments) {
33733             transformFlags |= 1 /* AssertTypeScript */;
33734         }
33735         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33736             // If the this node contains a SpreadElementExpression then it is an ES6
33737             // node.
33738             transformFlags |= 256 /* AssertES2015 */;
33739         }
33740         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33741         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33742     }
33743     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33744         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33745         if (node.typeArguments) {
33746             transformFlags |= 1 /* AssertTypeScript */;
33747         }
33748         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33749         return transformFlags & ~536870912 /* NodeExcludes */;
33750     }
33751     function computeBinaryExpression(node, subtreeFlags) {
33752         var transformFlags = subtreeFlags;
33753         var operatorTokenKind = node.operatorToken.kind;
33754         var leftKind = node.left.kind;
33755         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33756             transformFlags |= 8 /* AssertES2020 */;
33757         }
33758         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33759             // Destructuring object assignments with are ES2015 syntax
33760             // and possibly ES2018 if they contain rest
33761             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33762         }
33763         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33764             // Destructuring assignments are ES2015 syntax.
33765             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33766         }
33767         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33768             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33769             // Exponentiation is ES2016 syntax.
33770             transformFlags |= 128 /* AssertES2016 */;
33771         }
33772         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33773         return transformFlags & ~536870912 /* NodeExcludes */;
33774     }
33775     function computeParameter(node, subtreeFlags) {
33776         var transformFlags = subtreeFlags;
33777         var name = node.name;
33778         var initializer = node.initializer;
33779         var dotDotDotToken = node.dotDotDotToken;
33780         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33781         // syntax.
33782         if (node.questionToken
33783             || node.type
33784             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33785             || ts.isThisIdentifier(name)) {
33786             transformFlags |= 1 /* AssertTypeScript */;
33787         }
33788         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33789         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33790             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33791         }
33792         // parameters with object rest destructuring are ES2018 syntax
33793         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33794             transformFlags |= 32 /* AssertES2018 */;
33795         }
33796         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33797         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33798         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33799             transformFlags |= 256 /* AssertES2015 */;
33800         }
33801         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33802         return transformFlags & ~536870912 /* ParameterExcludes */;
33803     }
33804     function computeParenthesizedExpression(node, subtreeFlags) {
33805         var transformFlags = subtreeFlags;
33806         var expression = node.expression;
33807         var expressionKind = expression.kind;
33808         // If the node is synthesized, it means the emitter put the parentheses there,
33809         // not the user. If we didn't want them, the emitter would not have put them
33810         // there.
33811         if (expressionKind === 217 /* AsExpression */
33812             || expressionKind === 199 /* TypeAssertionExpression */) {
33813             transformFlags |= 1 /* AssertTypeScript */;
33814         }
33815         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33816         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33817     }
33818     function computeClassDeclaration(node, subtreeFlags) {
33819         var transformFlags;
33820         if (ts.hasModifier(node, 2 /* Ambient */)) {
33821             // An ambient declaration is TypeScript syntax.
33822             transformFlags = 1 /* AssertTypeScript */;
33823         }
33824         else {
33825             // A ClassDeclaration is ES6 syntax.
33826             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33827             // A class with a parameter property assignment or decorator is TypeScript syntax.
33828             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33829             // for a namespace declaration.
33830             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33831                 || node.typeParameters) {
33832                 transformFlags |= 1 /* AssertTypeScript */;
33833             }
33834         }
33835         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33836         return transformFlags & ~536905728 /* ClassExcludes */;
33837     }
33838     function computeClassExpression(node, subtreeFlags) {
33839         // A ClassExpression is ES6 syntax.
33840         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33841         // A class with a parameter property assignment or decorator is TypeScript syntax.
33842         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
33843             || node.typeParameters) {
33844             transformFlags |= 1 /* AssertTypeScript */;
33845         }
33846         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33847         return transformFlags & ~536905728 /* ClassExcludes */;
33848     }
33849     function computeHeritageClause(node, subtreeFlags) {
33850         var transformFlags = subtreeFlags;
33851         switch (node.token) {
33852             case 90 /* ExtendsKeyword */:
33853                 // An `extends` HeritageClause is ES6 syntax.
33854                 transformFlags |= 256 /* AssertES2015 */;
33855                 break;
33856             case 113 /* ImplementsKeyword */:
33857                 // An `implements` HeritageClause is TypeScript syntax.
33858                 transformFlags |= 1 /* AssertTypeScript */;
33859                 break;
33860             default:
33861                 ts.Debug.fail("Unexpected token for heritage clause");
33862                 break;
33863         }
33864         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33865         return transformFlags & ~536870912 /* NodeExcludes */;
33866     }
33867     function computeCatchClause(node, subtreeFlags) {
33868         var transformFlags = subtreeFlags;
33869         if (!node.variableDeclaration) {
33870             transformFlags |= 16 /* AssertES2019 */;
33871         }
33872         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
33873             transformFlags |= 256 /* AssertES2015 */;
33874         }
33875         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33876         return transformFlags & ~536887296 /* CatchClauseExcludes */;
33877     }
33878     function computeExpressionWithTypeArguments(node, subtreeFlags) {
33879         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
33880         // extends clause of a class.
33881         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33882         // If an ExpressionWithTypeArguments contains type arguments, then it
33883         // is TypeScript syntax.
33884         if (node.typeArguments) {
33885             transformFlags |= 1 /* AssertTypeScript */;
33886         }
33887         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33888         return transformFlags & ~536870912 /* NodeExcludes */;
33889     }
33890     function computeConstructor(node, subtreeFlags) {
33891         var transformFlags = subtreeFlags;
33892         // TypeScript-specific modifiers and overloads are TypeScript syntax
33893         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33894             || !node.body) {
33895             transformFlags |= 1 /* AssertTypeScript */;
33896         }
33897         // function declarations with object rest destructuring are ES2018 syntax
33898         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33899             transformFlags |= 32 /* AssertES2018 */;
33900         }
33901         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33902         return transformFlags & ~538923008 /* ConstructorExcludes */;
33903     }
33904     function computeMethod(node, subtreeFlags) {
33905         // A MethodDeclaration is ES6 syntax.
33906         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33907         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
33908         // overloads are TypeScript syntax.
33909         if (node.decorators
33910             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33911             || node.typeParameters
33912             || node.type
33913             || !node.body
33914             || node.questionToken) {
33915             transformFlags |= 1 /* AssertTypeScript */;
33916         }
33917         // function declarations with object rest destructuring are ES2018 syntax
33918         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33919             transformFlags |= 32 /* AssertES2018 */;
33920         }
33921         // An async method declaration is ES2017 syntax.
33922         if (ts.hasModifier(node, 256 /* Async */)) {
33923             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33924         }
33925         if (node.asteriskToken) {
33926             transformFlags |= 512 /* AssertGenerator */;
33927         }
33928         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33929         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33930     }
33931     function computeAccessor(node, subtreeFlags) {
33932         var transformFlags = subtreeFlags;
33933         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
33934         // TypeScript syntax.
33935         if (node.decorators
33936             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33937             || node.type
33938             || !node.body) {
33939             transformFlags |= 1 /* AssertTypeScript */;
33940         }
33941         // function declarations with object rest destructuring are ES2018 syntax
33942         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33943             transformFlags |= 32 /* AssertES2018 */;
33944         }
33945         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33946         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33947     }
33948     function computePropertyDeclaration(node, subtreeFlags) {
33949         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
33950         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
33951         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
33952             transformFlags |= 1 /* AssertTypeScript */;
33953         }
33954         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
33955         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
33956             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
33957         }
33958         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33959         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
33960     }
33961     function computeFunctionDeclaration(node, subtreeFlags) {
33962         var transformFlags;
33963         var modifierFlags = ts.getModifierFlags(node);
33964         var body = node.body;
33965         if (!body || (modifierFlags & 2 /* Ambient */)) {
33966             // An ambient declaration is TypeScript syntax.
33967             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
33968             transformFlags = 1 /* AssertTypeScript */;
33969         }
33970         else {
33971             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
33972             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
33973             // syntax.
33974             if (modifierFlags & 2270 /* TypeScriptModifier */
33975                 || node.typeParameters
33976                 || node.type) {
33977                 transformFlags |= 1 /* AssertTypeScript */;
33978             }
33979             // An async function declaration is ES2017 syntax.
33980             if (modifierFlags & 256 /* Async */) {
33981                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33982             }
33983             // function declarations with object rest destructuring are ES2018 syntax
33984             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33985                 transformFlags |= 32 /* AssertES2018 */;
33986             }
33987             // If a FunctionDeclaration is generator function and is the body of a
33988             // transformed async function, then this node can be transformed to a
33989             // down-level generator.
33990             // Currently we do not support transforming any other generator functions
33991             // down level.
33992             if (node.asteriskToken) {
33993                 transformFlags |= 512 /* AssertGenerator */;
33994             }
33995         }
33996         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33997         return transformFlags & ~538925056 /* FunctionExcludes */;
33998     }
33999     function computeFunctionExpression(node, subtreeFlags) {
34000         var transformFlags = subtreeFlags;
34001         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34002         // syntax.
34003         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34004             || node.typeParameters
34005             || node.type) {
34006             transformFlags |= 1 /* AssertTypeScript */;
34007         }
34008         // An async function expression is ES2017 syntax.
34009         if (ts.hasModifier(node, 256 /* Async */)) {
34010             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34011         }
34012         // function expressions with object rest destructuring are ES2018 syntax
34013         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34014             transformFlags |= 32 /* AssertES2018 */;
34015         }
34016         // If a FunctionExpression is generator function and is the body of a
34017         // transformed async function, then this node can be transformed to a
34018         // down-level generator.
34019         if (node.asteriskToken) {
34020             transformFlags |= 512 /* AssertGenerator */;
34021         }
34022         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34023         return transformFlags & ~538925056 /* FunctionExcludes */;
34024     }
34025     function computeArrowFunction(node, subtreeFlags) {
34026         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34027         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34028         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34029         // syntax.
34030         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34031             || node.typeParameters
34032             || node.type) {
34033             transformFlags |= 1 /* AssertTypeScript */;
34034         }
34035         // An async arrow function is ES2017 syntax.
34036         if (ts.hasModifier(node, 256 /* Async */)) {
34037             transformFlags |= 64 /* AssertES2017 */;
34038         }
34039         // arrow functions with object rest destructuring are ES2018 syntax
34040         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34041             transformFlags |= 32 /* AssertES2018 */;
34042         }
34043         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34044         return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
34045     }
34046     function computePropertyAccess(node, subtreeFlags) {
34047         var transformFlags = subtreeFlags;
34048         if (node.flags & 32 /* OptionalChain */) {
34049             transformFlags |= 8 /* ContainsES2020 */;
34050         }
34051         // If a PropertyAccessExpression starts with a super keyword, then it is
34052         // ES6 syntax, and requires a lexical `this` binding.
34053         if (node.expression.kind === 102 /* SuperKeyword */) {
34054             // super inside of an async function requires hoisting the super access (ES2017).
34055             // same for super inside of an async generator, which is ES2018.
34056             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34057         }
34058         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34059         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34060     }
34061     function computeElementAccess(node, subtreeFlags) {
34062         var transformFlags = subtreeFlags;
34063         if (node.flags & 32 /* OptionalChain */) {
34064             transformFlags |= 8 /* ContainsES2020 */;
34065         }
34066         // If an ElementAccessExpression starts with a super keyword, then it is
34067         // ES6 syntax, and requires a lexical `this` binding.
34068         if (node.expression.kind === 102 /* SuperKeyword */) {
34069             // super inside of an async function requires hoisting the super access (ES2017).
34070             // same for super inside of an async generator, which is ES2018.
34071             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34072         }
34073         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34074         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34075     }
34076     function computeVariableDeclaration(node, subtreeFlags) {
34077         var transformFlags = subtreeFlags;
34078         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34079         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34080         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34081             transformFlags |= 32 /* AssertES2018 */;
34082         }
34083         // Type annotations are TypeScript syntax.
34084         if (node.type || node.exclamationToken) {
34085             transformFlags |= 1 /* AssertTypeScript */;
34086         }
34087         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34088         return transformFlags & ~536870912 /* NodeExcludes */;
34089     }
34090     function computeVariableStatement(node, subtreeFlags) {
34091         var transformFlags;
34092         var declarationListTransformFlags = node.declarationList.transformFlags;
34093         // An ambient declaration is TypeScript syntax.
34094         if (ts.hasModifier(node, 2 /* Ambient */)) {
34095             transformFlags = 1 /* AssertTypeScript */;
34096         }
34097         else {
34098             transformFlags = subtreeFlags;
34099             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34100                 transformFlags |= 256 /* AssertES2015 */;
34101             }
34102         }
34103         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34104         return transformFlags & ~536870912 /* NodeExcludes */;
34105     }
34106     function computeLabeledStatement(node, subtreeFlags) {
34107         var transformFlags = subtreeFlags;
34108         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34109         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34110             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34111             transformFlags |= 256 /* AssertES2015 */;
34112         }
34113         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34114         return transformFlags & ~536870912 /* NodeExcludes */;
34115     }
34116     function computeImportEquals(node, subtreeFlags) {
34117         var transformFlags = subtreeFlags;
34118         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34119         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34120             transformFlags |= 1 /* AssertTypeScript */;
34121         }
34122         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34123         return transformFlags & ~536870912 /* NodeExcludes */;
34124     }
34125     function computeExpressionStatement(node, subtreeFlags) {
34126         var transformFlags = subtreeFlags;
34127         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34128         return transformFlags & ~536870912 /* NodeExcludes */;
34129     }
34130     function computeModuleDeclaration(node, subtreeFlags) {
34131         var transformFlags = 1 /* AssertTypeScript */;
34132         var modifierFlags = ts.getModifierFlags(node);
34133         if ((modifierFlags & 2 /* Ambient */) === 0) {
34134             transformFlags |= subtreeFlags;
34135         }
34136         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34137         return transformFlags & ~537991168 /* ModuleExcludes */;
34138     }
34139     function computeVariableDeclarationList(node, subtreeFlags) {
34140         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34141         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34142             transformFlags |= 256 /* AssertES2015 */;
34143         }
34144         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34145         if (node.flags & 3 /* BlockScoped */) {
34146             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34147         }
34148         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34149         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34150     }
34151     function computeOther(node, kind, subtreeFlags) {
34152         // Mark transformations needed for each node
34153         var transformFlags = subtreeFlags;
34154         var excludeFlags = 536870912 /* NodeExcludes */;
34155         switch (kind) {
34156             case 126 /* AsyncKeyword */:
34157                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34158                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34159                 break;
34160             case 206 /* AwaitExpression */:
34161                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34162                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34163                 break;
34164             case 199 /* TypeAssertionExpression */:
34165             case 217 /* AsExpression */:
34166             case 326 /* PartiallyEmittedExpression */:
34167                 // These nodes are TypeScript syntax.
34168                 transformFlags |= 1 /* AssertTypeScript */;
34169                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34170                 break;
34171             case 119 /* PublicKeyword */:
34172             case 117 /* PrivateKeyword */:
34173             case 118 /* ProtectedKeyword */:
34174             case 122 /* AbstractKeyword */:
34175             case 130 /* DeclareKeyword */:
34176             case 81 /* ConstKeyword */:
34177             case 248 /* EnumDeclaration */:
34178             case 284 /* EnumMember */:
34179             case 218 /* NonNullExpression */:
34180             case 138 /* ReadonlyKeyword */:
34181                 // These nodes are TypeScript syntax.
34182                 transformFlags |= 1 /* AssertTypeScript */;
34183                 break;
34184             case 266 /* JsxElement */:
34185             case 11 /* JsxText */:
34186             case 269 /* JsxClosingElement */:
34187             case 270 /* JsxFragment */:
34188             case 271 /* JsxOpeningFragment */:
34189             case 272 /* JsxClosingFragment */:
34190             case 273 /* JsxAttribute */:
34191             case 274 /* JsxAttributes */:
34192             case 275 /* JsxSpreadAttribute */:
34193             case 276 /* JsxExpression */:
34194                 // These nodes are Jsx syntax.
34195                 transformFlags |= 2 /* AssertJsx */;
34196                 break;
34197             case 14 /* NoSubstitutionTemplateLiteral */:
34198             case 15 /* TemplateHead */:
34199             case 16 /* TemplateMiddle */:
34200             case 17 /* TemplateTail */:
34201                 if (node.templateFlags) {
34202                     transformFlags |= 32 /* AssertES2018 */;
34203                     break;
34204                 }
34205             // falls through
34206             case 198 /* TaggedTemplateExpression */:
34207                 if (ts.hasInvalidEscape(node.template)) {
34208                     transformFlags |= 32 /* AssertES2018 */;
34209                     break;
34210                 }
34211             // falls through
34212             case 211 /* TemplateExpression */:
34213             case 282 /* ShorthandPropertyAssignment */:
34214             case 120 /* StaticKeyword */:
34215             case 219 /* MetaProperty */:
34216                 // These nodes are ES6 syntax.
34217                 transformFlags |= 256 /* AssertES2015 */;
34218                 break;
34219             case 10 /* StringLiteral */:
34220                 if (node.hasExtendedUnicodeEscape) {
34221                     transformFlags |= 256 /* AssertES2015 */;
34222                 }
34223                 break;
34224             case 8 /* NumericLiteral */:
34225                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34226                     transformFlags |= 256 /* AssertES2015 */;
34227                 }
34228                 break;
34229             case 9 /* BigIntLiteral */:
34230                 transformFlags |= 4 /* AssertESNext */;
34231                 break;
34232             case 232 /* ForOfStatement */:
34233                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34234                 if (node.awaitModifier) {
34235                     transformFlags |= 32 /* AssertES2018 */;
34236                 }
34237                 transformFlags |= 256 /* AssertES2015 */;
34238                 break;
34239             case 212 /* YieldExpression */:
34240                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34241                 // generator).
34242                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34243                 break;
34244             case 125 /* AnyKeyword */:
34245             case 140 /* NumberKeyword */:
34246             case 151 /* BigIntKeyword */:
34247             case 137 /* NeverKeyword */:
34248             case 141 /* ObjectKeyword */:
34249             case 143 /* StringKeyword */:
34250             case 128 /* BooleanKeyword */:
34251             case 144 /* SymbolKeyword */:
34252             case 110 /* VoidKeyword */:
34253             case 155 /* TypeParameter */:
34254             case 158 /* PropertySignature */:
34255             case 160 /* MethodSignature */:
34256             case 165 /* CallSignature */:
34257             case 166 /* ConstructSignature */:
34258             case 167 /* IndexSignature */:
34259             case 168 /* TypePredicate */:
34260             case 169 /* TypeReference */:
34261             case 170 /* FunctionType */:
34262             case 171 /* ConstructorType */:
34263             case 172 /* TypeQuery */:
34264             case 173 /* TypeLiteral */:
34265             case 174 /* ArrayType */:
34266             case 175 /* TupleType */:
34267             case 176 /* OptionalType */:
34268             case 177 /* RestType */:
34269             case 178 /* UnionType */:
34270             case 179 /* IntersectionType */:
34271             case 180 /* ConditionalType */:
34272             case 181 /* InferType */:
34273             case 182 /* ParenthesizedType */:
34274             case 246 /* InterfaceDeclaration */:
34275             case 247 /* TypeAliasDeclaration */:
34276             case 183 /* ThisType */:
34277             case 184 /* TypeOperator */:
34278             case 185 /* IndexedAccessType */:
34279             case 186 /* MappedType */:
34280             case 187 /* LiteralType */:
34281             case 252 /* NamespaceExportDeclaration */:
34282                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34283                 transformFlags = 1 /* AssertTypeScript */;
34284                 excludeFlags = -2 /* TypeExcludes */;
34285                 break;
34286             case 154 /* ComputedPropertyName */:
34287                 // Even though computed property names are ES6, we don't treat them as such.
34288                 // This is so that they can flow through PropertyName transforms unaffected.
34289                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34290                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34291                 break;
34292             case 213 /* SpreadElement */:
34293                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34294                 break;
34295             case 283 /* SpreadAssignment */:
34296                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34297                 break;
34298             case 102 /* SuperKeyword */:
34299                 // This node is ES6 syntax.
34300                 transformFlags |= 256 /* AssertES2015 */;
34301                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34302                 break;
34303             case 104 /* ThisKeyword */:
34304                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34305                 transformFlags |= 4096 /* ContainsLexicalThis */;
34306                 break;
34307             case 189 /* ObjectBindingPattern */:
34308                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34309                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34310                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34311                 }
34312                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34313                 break;
34314             case 190 /* ArrayBindingPattern */:
34315                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34316                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34317                 break;
34318             case 191 /* BindingElement */:
34319                 transformFlags |= 256 /* AssertES2015 */;
34320                 if (node.dotDotDotToken) {
34321                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34322                 }
34323                 break;
34324             case 157 /* Decorator */:
34325                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34326                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34327                 break;
34328             case 193 /* ObjectLiteralExpression */:
34329                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34330                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34331                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34332                     // is an ES6 node.
34333                     transformFlags |= 256 /* AssertES2015 */;
34334                 }
34335                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34336                     // If an ObjectLiteralExpression contains a spread element, then it
34337                     // is an ES2018 node.
34338                     transformFlags |= 32 /* AssertES2018 */;
34339                 }
34340                 break;
34341             case 192 /* ArrayLiteralExpression */:
34342                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34343                 break;
34344             case 228 /* DoStatement */:
34345             case 229 /* WhileStatement */:
34346             case 230 /* ForStatement */:
34347             case 231 /* ForInStatement */:
34348                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34349                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34350                     transformFlags |= 256 /* AssertES2015 */;
34351                 }
34352                 break;
34353             case 290 /* SourceFile */:
34354                 break;
34355             case 262 /* NamespaceExport */:
34356                 transformFlags |= 4 /* AssertESNext */;
34357                 break;
34358             case 235 /* ReturnStatement */:
34359                 // Return statements may require an `await` in ES2018.
34360                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34361                 break;
34362             case 233 /* ContinueStatement */:
34363             case 234 /* BreakStatement */:
34364                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34365                 break;
34366             case 76 /* PrivateIdentifier */:
34367                 transformFlags |= 4194304 /* ContainsClassFields */;
34368                 break;
34369         }
34370         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34371         return transformFlags & ~excludeFlags;
34372     }
34373     function propagatePropertyNameFlags(node, transformFlags) {
34374         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34375     }
34376     /**
34377      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34378      *
34379      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34380      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34381      *       than calling this function.
34382      */
34383     function getTransformFlagsSubtreeExclusions(kind) {
34384         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34385             return -2 /* TypeExcludes */;
34386         }
34387         switch (kind) {
34388             case 196 /* CallExpression */:
34389             case 197 /* NewExpression */:
34390             case 192 /* ArrayLiteralExpression */:
34391                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34392             case 249 /* ModuleDeclaration */:
34393                 return 537991168 /* ModuleExcludes */;
34394             case 156 /* Parameter */:
34395                 return 536870912 /* ParameterExcludes */;
34396             case 202 /* ArrowFunction */:
34397                 return 538920960 /* ArrowFunctionExcludes */;
34398             case 201 /* FunctionExpression */:
34399             case 244 /* FunctionDeclaration */:
34400                 return 538925056 /* FunctionExcludes */;
34401             case 243 /* VariableDeclarationList */:
34402                 return 537018368 /* VariableDeclarationListExcludes */;
34403             case 245 /* ClassDeclaration */:
34404             case 214 /* ClassExpression */:
34405                 return 536905728 /* ClassExcludes */;
34406             case 162 /* Constructor */:
34407                 return 538923008 /* ConstructorExcludes */;
34408             case 161 /* MethodDeclaration */:
34409             case 163 /* GetAccessor */:
34410             case 164 /* SetAccessor */:
34411                 return 538923008 /* MethodOrAccessorExcludes */;
34412             case 125 /* AnyKeyword */:
34413             case 140 /* NumberKeyword */:
34414             case 151 /* BigIntKeyword */:
34415             case 137 /* NeverKeyword */:
34416             case 143 /* StringKeyword */:
34417             case 141 /* ObjectKeyword */:
34418             case 128 /* BooleanKeyword */:
34419             case 144 /* SymbolKeyword */:
34420             case 110 /* VoidKeyword */:
34421             case 155 /* TypeParameter */:
34422             case 158 /* PropertySignature */:
34423             case 160 /* MethodSignature */:
34424             case 165 /* CallSignature */:
34425             case 166 /* ConstructSignature */:
34426             case 167 /* IndexSignature */:
34427             case 246 /* InterfaceDeclaration */:
34428             case 247 /* TypeAliasDeclaration */:
34429                 return -2 /* TypeExcludes */;
34430             case 193 /* ObjectLiteralExpression */:
34431                 return 536922112 /* ObjectLiteralExcludes */;
34432             case 280 /* CatchClause */:
34433                 return 536887296 /* CatchClauseExcludes */;
34434             case 189 /* ObjectBindingPattern */:
34435             case 190 /* ArrayBindingPattern */:
34436                 return 536879104 /* BindingPatternExcludes */;
34437             case 199 /* TypeAssertionExpression */:
34438             case 217 /* AsExpression */:
34439             case 326 /* PartiallyEmittedExpression */:
34440             case 200 /* ParenthesizedExpression */:
34441             case 102 /* SuperKeyword */:
34442                 return 536870912 /* OuterExpressionExcludes */;
34443             case 194 /* PropertyAccessExpression */:
34444             case 195 /* ElementAccessExpression */:
34445                 return 536870912 /* PropertyAccessExcludes */;
34446             default:
34447                 return 536870912 /* NodeExcludes */;
34448         }
34449     }
34450     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34451     /**
34452      * "Binds" JSDoc nodes in TypeScript code.
34453      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34454      */
34455     function setParentPointers(parent, child) {
34456         child.parent = parent;
34457         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34458     }
34459 })(ts || (ts = {}));
34460 /** @internal */
34461 var ts;
34462 (function (ts) {
34463     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34464         return getSymbolWalker;
34465         function getSymbolWalker(accept) {
34466             if (accept === void 0) { accept = function () { return true; }; }
34467             var visitedTypes = []; // Sparse array from id to type
34468             var visitedSymbols = []; // Sparse array from id to symbol
34469             return {
34470                 walkType: function (type) {
34471                     try {
34472                         visitType(type);
34473                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34474                     }
34475                     finally {
34476                         ts.clear(visitedTypes);
34477                         ts.clear(visitedSymbols);
34478                     }
34479                 },
34480                 walkSymbol: function (symbol) {
34481                     try {
34482                         visitSymbol(symbol);
34483                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34484                     }
34485                     finally {
34486                         ts.clear(visitedTypes);
34487                         ts.clear(visitedSymbols);
34488                     }
34489                 },
34490             };
34491             function visitType(type) {
34492                 if (!type) {
34493                     return;
34494                 }
34495                 if (visitedTypes[type.id]) {
34496                     return;
34497                 }
34498                 visitedTypes[type.id] = type;
34499                 // Reuse visitSymbol to visit the type's symbol,
34500                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34501                 var shouldBail = visitSymbol(type.symbol);
34502                 if (shouldBail)
34503                     return;
34504                 // Visit the type's related types, if any
34505                 if (type.flags & 524288 /* Object */) {
34506                     var objectType = type;
34507                     var objectFlags = objectType.objectFlags;
34508                     if (objectFlags & 4 /* Reference */) {
34509                         visitTypeReference(type);
34510                     }
34511                     if (objectFlags & 32 /* Mapped */) {
34512                         visitMappedType(type);
34513                     }
34514                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34515                         visitInterfaceType(type);
34516                     }
34517                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34518                         visitObjectType(objectType);
34519                     }
34520                 }
34521                 if (type.flags & 262144 /* TypeParameter */) {
34522                     visitTypeParameter(type);
34523                 }
34524                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34525                     visitUnionOrIntersectionType(type);
34526                 }
34527                 if (type.flags & 4194304 /* Index */) {
34528                     visitIndexType(type);
34529                 }
34530                 if (type.flags & 8388608 /* IndexedAccess */) {
34531                     visitIndexedAccessType(type);
34532                 }
34533             }
34534             function visitTypeReference(type) {
34535                 visitType(type.target);
34536                 ts.forEach(getTypeArguments(type), visitType);
34537             }
34538             function visitTypeParameter(type) {
34539                 visitType(getConstraintOfTypeParameter(type));
34540             }
34541             function visitUnionOrIntersectionType(type) {
34542                 ts.forEach(type.types, visitType);
34543             }
34544             function visitIndexType(type) {
34545                 visitType(type.type);
34546             }
34547             function visitIndexedAccessType(type) {
34548                 visitType(type.objectType);
34549                 visitType(type.indexType);
34550                 visitType(type.constraint);
34551             }
34552             function visitMappedType(type) {
34553                 visitType(type.typeParameter);
34554                 visitType(type.constraintType);
34555                 visitType(type.templateType);
34556                 visitType(type.modifiersType);
34557             }
34558             function visitSignature(signature) {
34559                 var typePredicate = getTypePredicateOfSignature(signature);
34560                 if (typePredicate) {
34561                     visitType(typePredicate.type);
34562                 }
34563                 ts.forEach(signature.typeParameters, visitType);
34564                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34565                     var parameter = _a[_i];
34566                     visitSymbol(parameter);
34567                 }
34568                 visitType(getRestTypeOfSignature(signature));
34569                 visitType(getReturnTypeOfSignature(signature));
34570             }
34571             function visitInterfaceType(interfaceT) {
34572                 visitObjectType(interfaceT);
34573                 ts.forEach(interfaceT.typeParameters, visitType);
34574                 ts.forEach(getBaseTypes(interfaceT), visitType);
34575                 visitType(interfaceT.thisType);
34576             }
34577             function visitObjectType(type) {
34578                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34579                 visitType(stringIndexType);
34580                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34581                 visitType(numberIndexType);
34582                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34583                 var resolved = resolveStructuredTypeMembers(type);
34584                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34585                     var signature = _a[_i];
34586                     visitSignature(signature);
34587                 }
34588                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34589                     var signature = _c[_b];
34590                     visitSignature(signature);
34591                 }
34592                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34593                     var p = _e[_d];
34594                     visitSymbol(p);
34595                 }
34596             }
34597             function visitSymbol(symbol) {
34598                 if (!symbol) {
34599                     return false;
34600                 }
34601                 var symbolId = ts.getSymbolId(symbol);
34602                 if (visitedSymbols[symbolId]) {
34603                     return false;
34604                 }
34605                 visitedSymbols[symbolId] = symbol;
34606                 if (!accept(symbol)) {
34607                     return true;
34608                 }
34609                 var t = getTypeOfSymbol(symbol);
34610                 visitType(t); // Should handle members on classes and such
34611                 if (symbol.exports) {
34612                     symbol.exports.forEach(visitSymbol);
34613                 }
34614                 ts.forEach(symbol.declarations, function (d) {
34615                     // Type queries are too far resolved when we just visit the symbol's type
34616                     //  (their type resolved directly to the member deeply referenced)
34617                     // So to get the intervening symbols, we need to check if there's a type
34618                     // query node on any of the symbol's declarations and get symbols there
34619                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34620                         var query = d.type;
34621                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34622                         visitSymbol(entity);
34623                     }
34624                 });
34625                 return false;
34626             }
34627         }
34628     }
34629     ts.createGetSymbolWalker = createGetSymbolWalker;
34630 })(ts || (ts = {}));
34631 /* @internal */
34632 var ts;
34633 (function (ts) {
34634     var ambientModuleSymbolRegex = /^".+"$/;
34635     var anon = "(anonymous)";
34636     var nextSymbolId = 1;
34637     var nextNodeId = 1;
34638     var nextMergeId = 1;
34639     var nextFlowId = 1;
34640     var IterationUse;
34641     (function (IterationUse) {
34642         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34643         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34644         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34645         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34646         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34647         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34648         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34649         // Spread, Destructuring, Array element assignment
34650         IterationUse[IterationUse["Element"] = 1] = "Element";
34651         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34652         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34653         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34654         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34655         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34656         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34657         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34658         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34659     })(IterationUse || (IterationUse = {}));
34660     var IterationTypeKind;
34661     (function (IterationTypeKind) {
34662         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34663         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34664         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34665     })(IterationTypeKind || (IterationTypeKind = {}));
34666     var WideningKind;
34667     (function (WideningKind) {
34668         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34669         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34670         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34671         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34672     })(WideningKind || (WideningKind = {}));
34673     var TypeFacts;
34674     (function (TypeFacts) {
34675         TypeFacts[TypeFacts["None"] = 0] = "None";
34676         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34677         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34678         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34679         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34680         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34681         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34682         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34683         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34684         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34685         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34686         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34687         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34688         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34689         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34690         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34691         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34692         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34693         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34694         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34695         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34696         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34697         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34698         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34699         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34700         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34701         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34702         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34703         // of that kind of type.
34704         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34705         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34706         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34707         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34708         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34709         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34710         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34711         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34712         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34713         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34714         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34715         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34716         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34717         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34718         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34719         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34720         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34721         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34722         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34723         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34724         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34725         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34726         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34727         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34728         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34729         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34730         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34731         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34732         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34733         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34734         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34735         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34736         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34737         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34738         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34739         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34740         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34741         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34742         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34743         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34744         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34745         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34746     })(TypeFacts || (TypeFacts = {}));
34747     var typeofEQFacts = ts.createMapFromTemplate({
34748         string: 1 /* TypeofEQString */,
34749         number: 2 /* TypeofEQNumber */,
34750         bigint: 4 /* TypeofEQBigInt */,
34751         boolean: 8 /* TypeofEQBoolean */,
34752         symbol: 16 /* TypeofEQSymbol */,
34753         undefined: 65536 /* EQUndefined */,
34754         object: 32 /* TypeofEQObject */,
34755         function: 64 /* TypeofEQFunction */
34756     });
34757     var typeofNEFacts = ts.createMapFromTemplate({
34758         string: 256 /* TypeofNEString */,
34759         number: 512 /* TypeofNENumber */,
34760         bigint: 1024 /* TypeofNEBigInt */,
34761         boolean: 2048 /* TypeofNEBoolean */,
34762         symbol: 4096 /* TypeofNESymbol */,
34763         undefined: 524288 /* NEUndefined */,
34764         object: 8192 /* TypeofNEObject */,
34765         function: 16384 /* TypeofNEFunction */
34766     });
34767     var TypeSystemPropertyName;
34768     (function (TypeSystemPropertyName) {
34769         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34770         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34771         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34772         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34773         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34774         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34775         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34776     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34777     var CheckMode;
34778     (function (CheckMode) {
34779         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34780         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34781         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34782         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34783         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34784         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34785     })(CheckMode || (CheckMode = {}));
34786     var AccessFlags;
34787     (function (AccessFlags) {
34788         AccessFlags[AccessFlags["None"] = 0] = "None";
34789         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34790         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34791         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34792         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34793     })(AccessFlags || (AccessFlags = {}));
34794     var SignatureCheckMode;
34795     (function (SignatureCheckMode) {
34796         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34797         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34798         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34799         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34800         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34801     })(SignatureCheckMode || (SignatureCheckMode = {}));
34802     var IntersectionState;
34803     (function (IntersectionState) {
34804         IntersectionState[IntersectionState["None"] = 0] = "None";
34805         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34806         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34807         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34808         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34809     })(IntersectionState || (IntersectionState = {}));
34810     var MappedTypeModifiers;
34811     (function (MappedTypeModifiers) {
34812         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34813         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34814         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34815         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34816     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34817     var ExpandingFlags;
34818     (function (ExpandingFlags) {
34819         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34820         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34821         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34822         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34823     })(ExpandingFlags || (ExpandingFlags = {}));
34824     var MembersOrExportsResolutionKind;
34825     (function (MembersOrExportsResolutionKind) {
34826         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34827         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34828     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34829     var UnusedKind;
34830     (function (UnusedKind) {
34831         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34832         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34833     })(UnusedKind || (UnusedKind = {}));
34834     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34835     var DeclarationMeaning;
34836     (function (DeclarationMeaning) {
34837         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
34838         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
34839         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
34840         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
34841         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
34842         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
34843     })(DeclarationMeaning || (DeclarationMeaning = {}));
34844     var DeclarationSpaces;
34845     (function (DeclarationSpaces) {
34846         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
34847         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
34848         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
34849         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
34850     })(DeclarationSpaces || (DeclarationSpaces = {}));
34851     function SymbolLinks() {
34852     }
34853     function NodeLinks() {
34854         this.flags = 0;
34855     }
34856     function getNodeId(node) {
34857         if (!node.id) {
34858             node.id = nextNodeId;
34859             nextNodeId++;
34860         }
34861         return node.id;
34862     }
34863     ts.getNodeId = getNodeId;
34864     function getSymbolId(symbol) {
34865         if (!symbol.id) {
34866             symbol.id = nextSymbolId;
34867             nextSymbolId++;
34868         }
34869         return symbol.id;
34870     }
34871     ts.getSymbolId = getSymbolId;
34872     function isInstantiatedModule(node, preserveConstEnums) {
34873         var moduleState = ts.getModuleInstanceState(node);
34874         return moduleState === 1 /* Instantiated */ ||
34875             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
34876     }
34877     ts.isInstantiatedModule = isInstantiatedModule;
34878     function createTypeChecker(host, produceDiagnostics) {
34879         var getPackagesSet = ts.memoize(function () {
34880             var set = ts.createMap();
34881             host.getSourceFiles().forEach(function (sf) {
34882                 if (!sf.resolvedModules)
34883                     return;
34884                 ts.forEachEntry(sf.resolvedModules, function (r) {
34885                     if (r && r.packageId)
34886                         set.set(r.packageId.name, true);
34887                 });
34888             });
34889             return set;
34890         });
34891         // Cancellation that controls whether or not we can cancel in the middle of type checking.
34892         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
34893         // computing something, and we will leave our internals in an inconsistent state.  Callers
34894         // who set the cancellation token should catch if a cancellation exception occurs, and
34895         // should throw away and create a new TypeChecker.
34896         //
34897         // Currently we only support setting the cancellation token when getting diagnostics.  This
34898         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
34899         // they no longer need the information (for example, if the user started editing again).
34900         var cancellationToken;
34901         var requestedExternalEmitHelpers;
34902         var externalHelpersModule;
34903         var Symbol = ts.objectAllocator.getSymbolConstructor();
34904         var Type = ts.objectAllocator.getTypeConstructor();
34905         var Signature = ts.objectAllocator.getSignatureConstructor();
34906         var typeCount = 0;
34907         var symbolCount = 0;
34908         var enumCount = 0;
34909         var totalInstantiationCount = 0;
34910         var instantiationCount = 0;
34911         var instantiationDepth = 0;
34912         var constraintDepth = 0;
34913         var currentNode;
34914         var emptySymbols = ts.createSymbolTable();
34915         var arrayVariances = [1 /* Covariant */];
34916         var compilerOptions = host.getCompilerOptions();
34917         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
34918         var moduleKind = ts.getEmitModuleKind(compilerOptions);
34919         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
34920         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
34921         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
34922         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
34923         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
34924         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
34925         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
34926         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
34927         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
34928         var emitResolver = createResolver();
34929         var nodeBuilder = createNodeBuilder();
34930         var globals = ts.createSymbolTable();
34931         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
34932         undefinedSymbol.declarations = [];
34933         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
34934         globalThisSymbol.exports = globals;
34935         globalThisSymbol.declarations = [];
34936         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
34937         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
34938         var requireSymbol = createSymbol(4 /* Property */, "require");
34939         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
34940         var apparentArgumentCount;
34941         // for public members that accept a Node or one of its subtypes, we must guard against
34942         // synthetic nodes created during transformations by calling `getParseTreeNode`.
34943         // for most of these, we perform the guard only on `checker` to avoid any possible
34944         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
34945         // checker.
34946         var checker = {
34947             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
34948             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
34949             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
34950             getTypeCount: function () { return typeCount; },
34951             getInstantiationCount: function () { return totalInstantiationCount; },
34952             getRelationCacheSizes: function () { return ({
34953                 assignable: assignableRelation.size,
34954                 identity: identityRelation.size,
34955                 subtype: subtypeRelation.size,
34956                 strictSubtype: strictSubtypeRelation.size,
34957             }); },
34958             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
34959             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
34960             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
34961             getMergedSymbol: getMergedSymbol,
34962             getDiagnostics: getDiagnostics,
34963             getGlobalDiagnostics: getGlobalDiagnostics,
34964             getTypeOfSymbolAtLocation: function (symbol, location) {
34965                 location = ts.getParseTreeNode(location);
34966                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
34967             },
34968             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
34969                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
34970                 if (parameter === undefined)
34971                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
34972                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
34973             },
34974             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
34975             getPropertiesOfType: getPropertiesOfType,
34976             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34977             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
34978                 var node = ts.getParseTreeNode(location);
34979                 if (!node) {
34980                     return undefined;
34981                 }
34982                 var propName = ts.escapeLeadingUnderscores(name);
34983                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
34984                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
34985             },
34986             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34987             getIndexInfoOfType: getIndexInfoOfType,
34988             getSignaturesOfType: getSignaturesOfType,
34989             getIndexTypeOfType: getIndexTypeOfType,
34990             getBaseTypes: getBaseTypes,
34991             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
34992             getWidenedType: getWidenedType,
34993             getTypeFromTypeNode: function (nodeIn) {
34994                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
34995                 return node ? getTypeFromTypeNode(node) : errorType;
34996             },
34997             getParameterType: getTypeAtPosition,
34998             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
34999             getReturnTypeOfSignature: getReturnTypeOfSignature,
35000             isNullableType: isNullableType,
35001             getNullableType: getNullableType,
35002             getNonNullableType: getNonNullableType,
35003             getNonOptionalType: removeOptionalTypeMarker,
35004             getTypeArguments: getTypeArguments,
35005             typeToTypeNode: nodeBuilder.typeToTypeNode,
35006             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35007             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35008             symbolToEntityName: nodeBuilder.symbolToEntityName,
35009             symbolToExpression: nodeBuilder.symbolToExpression,
35010             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35011             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35012             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35013             getSymbolsInScope: function (location, meaning) {
35014                 location = ts.getParseTreeNode(location);
35015                 return location ? getSymbolsInScope(location, meaning) : [];
35016             },
35017             getSymbolAtLocation: function (node) {
35018                 node = ts.getParseTreeNode(node);
35019                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35020                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35021             },
35022             getShorthandAssignmentValueSymbol: function (node) {
35023                 node = ts.getParseTreeNode(node);
35024                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35025             },
35026             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35027                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35028                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35029             },
35030             getExportSymbolOfSymbol: function (symbol) {
35031                 return getMergedSymbol(symbol.exportSymbol || symbol);
35032             },
35033             getTypeAtLocation: function (node) {
35034                 node = ts.getParseTreeNode(node);
35035                 return node ? getTypeOfNode(node) : errorType;
35036             },
35037             getTypeOfAssignmentPattern: function (nodeIn) {
35038                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35039                 return node && getTypeOfAssignmentPattern(node) || errorType;
35040             },
35041             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35042                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35043                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35044             },
35045             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35046                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35047             },
35048             typeToString: function (type, enclosingDeclaration, flags) {
35049                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35050             },
35051             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35052                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35053             },
35054             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35055                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35056             },
35057             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35058                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35059             },
35060             writeType: function (type, enclosingDeclaration, flags, writer) {
35061                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35062             },
35063             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35064                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35065             },
35066             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35067                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35068             },
35069             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35070             getRootSymbols: getRootSymbols,
35071             getContextualType: function (nodeIn, contextFlags) {
35072                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35073                 if (!node) {
35074                     return undefined;
35075                 }
35076                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35077                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35078                 if (contextFlags & 4 /* Completions */ && containingCall) {
35079                     var toMarkSkip = node;
35080                     do {
35081                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35082                         toMarkSkip = toMarkSkip.parent;
35083                     } while (toMarkSkip && toMarkSkip !== containingCall);
35084                     getNodeLinks(containingCall).resolvedSignature = undefined;
35085                 }
35086                 var result = getContextualType(node, contextFlags);
35087                 if (contextFlags & 4 /* Completions */ && containingCall) {
35088                     var toMarkSkip = node;
35089                     do {
35090                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35091                         toMarkSkip = toMarkSkip.parent;
35092                     } while (toMarkSkip && toMarkSkip !== containingCall);
35093                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35094                 }
35095                 return result;
35096             },
35097             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35098                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35099                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35100             },
35101             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35102                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35103                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35104             },
35105             getContextualTypeForJsxAttribute: function (nodeIn) {
35106                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35107                 return node && getContextualTypeForJsxAttribute(node);
35108             },
35109             isContextSensitive: isContextSensitive,
35110             getFullyQualifiedName: getFullyQualifiedName,
35111             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35112                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35113             },
35114             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35115                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35116             },
35117             getExpandedParameters: getExpandedParameters,
35118             hasEffectiveRestParameter: hasEffectiveRestParameter,
35119             getConstantValue: function (nodeIn) {
35120                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35121                 return node ? getConstantValue(node) : undefined;
35122             },
35123             isValidPropertyAccess: function (nodeIn, propertyName) {
35124                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35125                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35126             },
35127             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35128                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35129                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35130             },
35131             getSignatureFromDeclaration: function (declarationIn) {
35132                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35133                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35134             },
35135             isImplementationOfOverload: function (node) {
35136                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35137                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35138             },
35139             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35140             getAliasedSymbol: resolveAlias,
35141             getEmitResolver: getEmitResolver,
35142             getExportsOfModule: getExportsOfModuleAsArray,
35143             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35144             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35145             getAmbientModules: getAmbientModules,
35146             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35147             isOptionalParameter: function (nodeIn) {
35148                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35149                 return node ? isOptionalParameter(node) : false;
35150             },
35151             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35152             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35153             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35154                 // we deliberately exclude augmentations
35155                 // since we are only interested in declarations of the module itself
35156                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35157             },
35158             getApparentType: getApparentType,
35159             getUnionType: getUnionType,
35160             isTypeAssignableTo: isTypeAssignableTo,
35161             createAnonymousType: createAnonymousType,
35162             createSignature: createSignature,
35163             createSymbol: createSymbol,
35164             createIndexInfo: createIndexInfo,
35165             getAnyType: function () { return anyType; },
35166             getStringType: function () { return stringType; },
35167             getNumberType: function () { return numberType; },
35168             createPromiseType: createPromiseType,
35169             createArrayType: createArrayType,
35170             getElementTypeOfArrayType: getElementTypeOfArrayType,
35171             getBooleanType: function () { return booleanType; },
35172             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35173             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35174             getVoidType: function () { return voidType; },
35175             getUndefinedType: function () { return undefinedType; },
35176             getNullType: function () { return nullType; },
35177             getESSymbolType: function () { return esSymbolType; },
35178             getNeverType: function () { return neverType; },
35179             getOptionalType: function () { return optionalType; },
35180             isSymbolAccessible: isSymbolAccessible,
35181             isArrayType: isArrayType,
35182             isTupleType: isTupleType,
35183             isArrayLikeType: isArrayLikeType,
35184             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35185             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35186             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35187             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35188             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35189             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35190             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35191             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35192             getBaseConstraintOfType: getBaseConstraintOfType,
35193             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35194             resolveName: function (name, location, meaning, excludeGlobals) {
35195                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35196             },
35197             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35198             getAccessibleSymbolChain: getAccessibleSymbolChain,
35199             getTypePredicateOfSignature: getTypePredicateOfSignature,
35200             resolveExternalModuleName: function (moduleSpecifier) {
35201                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35202             },
35203             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35204             tryGetThisTypeAt: function (node, includeGlobalThis) {
35205                 node = ts.getParseTreeNode(node);
35206                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35207             },
35208             getTypeArgumentConstraint: function (nodeIn) {
35209                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35210                 return node && getTypeArgumentConstraint(node);
35211             },
35212             getSuggestionDiagnostics: function (file, ct) {
35213                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35214                     return ts.emptyArray;
35215                 }
35216                 var diagnostics;
35217                 try {
35218                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35219                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35220                     // this call is done.
35221                     cancellationToken = ct;
35222                     // Ensure file is type checked
35223                     checkSourceFile(file);
35224                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35225                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35226                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35227                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35228                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35229                         }
35230                     });
35231                     return diagnostics || ts.emptyArray;
35232                 }
35233                 finally {
35234                     cancellationToken = undefined;
35235                 }
35236             },
35237             runWithCancellationToken: function (token, callback) {
35238                 try {
35239                     cancellationToken = token;
35240                     return callback(checker);
35241                 }
35242                 finally {
35243                     cancellationToken = undefined;
35244                 }
35245             },
35246             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35247             isDeclarationVisible: isDeclarationVisible,
35248         };
35249         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35250             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35251             apparentArgumentCount = argumentCount;
35252             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35253             apparentArgumentCount = undefined;
35254             return res;
35255         }
35256         var tupleTypes = ts.createMap();
35257         var unionTypes = ts.createMap();
35258         var intersectionTypes = ts.createMap();
35259         var literalTypes = ts.createMap();
35260         var indexedAccessTypes = ts.createMap();
35261         var substitutionTypes = ts.createMap();
35262         var evolvingArrayTypes = [];
35263         var undefinedProperties = ts.createMap();
35264         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35265         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35266         var anyType = createIntrinsicType(1 /* Any */, "any");
35267         var autoType = createIntrinsicType(1 /* Any */, "any");
35268         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35269         var errorType = createIntrinsicType(1 /* Any */, "error");
35270         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35271         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35272         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35273         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35274         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35275         var nullType = createIntrinsicType(65536 /* Null */, "null");
35276         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35277         var stringType = createIntrinsicType(4 /* String */, "string");
35278         var numberType = createIntrinsicType(8 /* Number */, "number");
35279         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35280         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35281         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35282         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35283         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35284         trueType.regularType = regularTrueType;
35285         trueType.freshType = trueType;
35286         regularTrueType.regularType = regularTrueType;
35287         regularTrueType.freshType = trueType;
35288         falseType.regularType = regularFalseType;
35289         falseType.freshType = falseType;
35290         regularFalseType.regularType = regularFalseType;
35291         regularFalseType.freshType = falseType;
35292         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35293         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35294         // (The union is cached, so simply doing the marking here is sufficient)
35295         createBooleanType([regularFalseType, trueType]);
35296         createBooleanType([falseType, regularTrueType]);
35297         createBooleanType([falseType, trueType]);
35298         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35299         var voidType = createIntrinsicType(16384 /* Void */, "void");
35300         var neverType = createIntrinsicType(131072 /* Never */, "never");
35301         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35302         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35303         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35304         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35305         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35306         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35307         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35308         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35309         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35310         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35311         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35312         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35313         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35314         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35315         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35316         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35317         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35318         emptyGenericType.instantiations = ts.createMap();
35319         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35320         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35321         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35322         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35323         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35324         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35325         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35326         var markerSuperType = createTypeParameter();
35327         var markerSubType = createTypeParameter();
35328         markerSubType.constraint = markerSuperType;
35329         var markerOtherType = createTypeParameter();
35330         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35331         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35332         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35333         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35334         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35335         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35336         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35337         var noIterationTypes = {
35338             get yieldType() { return ts.Debug.fail("Not supported"); },
35339             get returnType() { return ts.Debug.fail("Not supported"); },
35340             get nextType() { return ts.Debug.fail("Not supported"); },
35341         };
35342         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35343         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35344         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35345         var asyncIterationTypesResolver = {
35346             iterableCacheKey: "iterationTypesOfAsyncIterable",
35347             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35348             iteratorSymbolName: "asyncIterator",
35349             getGlobalIteratorType: getGlobalAsyncIteratorType,
35350             getGlobalIterableType: getGlobalAsyncIterableType,
35351             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35352             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35353             resolveIterationType: getAwaitedType,
35354             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35355             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35356             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,
35357         };
35358         var syncIterationTypesResolver = {
35359             iterableCacheKey: "iterationTypesOfIterable",
35360             iteratorCacheKey: "iterationTypesOfIterator",
35361             iteratorSymbolName: "iterator",
35362             getGlobalIteratorType: getGlobalIteratorType,
35363             getGlobalIterableType: getGlobalIterableType,
35364             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35365             getGlobalGeneratorType: getGlobalGeneratorType,
35366             resolveIterationType: function (type, _errorNode) { return type; },
35367             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35368             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35369             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35370         };
35371         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35372         var amalgamatedDuplicates;
35373         var reverseMappedCache = ts.createMap();
35374         var ambientModulesCache;
35375         /**
35376          * List of every ambient module with a "*" wildcard.
35377          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35378          * This is only used if there is no exact match.
35379          */
35380         var patternAmbientModules;
35381         var patternAmbientModuleAugmentations;
35382         var globalObjectType;
35383         var globalFunctionType;
35384         var globalCallableFunctionType;
35385         var globalNewableFunctionType;
35386         var globalArrayType;
35387         var globalReadonlyArrayType;
35388         var globalStringType;
35389         var globalNumberType;
35390         var globalBooleanType;
35391         var globalRegExpType;
35392         var globalThisType;
35393         var anyArrayType;
35394         var autoArrayType;
35395         var anyReadonlyArrayType;
35396         var deferredGlobalNonNullableTypeAlias;
35397         // The library files are only loaded when the feature is used.
35398         // This allows users to just specify library files they want to used through --lib
35399         // and they will not get an error from not having unrelated library files
35400         var deferredGlobalESSymbolConstructorSymbol;
35401         var deferredGlobalESSymbolType;
35402         var deferredGlobalTypedPropertyDescriptorType;
35403         var deferredGlobalPromiseType;
35404         var deferredGlobalPromiseLikeType;
35405         var deferredGlobalPromiseConstructorSymbol;
35406         var deferredGlobalPromiseConstructorLikeType;
35407         var deferredGlobalIterableType;
35408         var deferredGlobalIteratorType;
35409         var deferredGlobalIterableIteratorType;
35410         var deferredGlobalGeneratorType;
35411         var deferredGlobalIteratorYieldResultType;
35412         var deferredGlobalIteratorReturnResultType;
35413         var deferredGlobalAsyncIterableType;
35414         var deferredGlobalAsyncIteratorType;
35415         var deferredGlobalAsyncIterableIteratorType;
35416         var deferredGlobalAsyncGeneratorType;
35417         var deferredGlobalTemplateStringsArrayType;
35418         var deferredGlobalImportMetaType;
35419         var deferredGlobalExtractSymbol;
35420         var deferredGlobalOmitSymbol;
35421         var deferredGlobalBigIntType;
35422         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35423         var flowLoopStart = 0;
35424         var flowLoopCount = 0;
35425         var sharedFlowCount = 0;
35426         var flowAnalysisDisabled = false;
35427         var flowInvocationCount = 0;
35428         var lastFlowNode;
35429         var lastFlowNodeReachable;
35430         var flowTypeCache;
35431         var emptyStringType = getLiteralType("");
35432         var zeroType = getLiteralType(0);
35433         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35434         var resolutionTargets = [];
35435         var resolutionResults = [];
35436         var resolutionPropertyNames = [];
35437         var suggestionCount = 0;
35438         var maximumSuggestionCount = 10;
35439         var mergedSymbols = [];
35440         var symbolLinks = [];
35441         var nodeLinks = [];
35442         var flowLoopCaches = [];
35443         var flowLoopNodes = [];
35444         var flowLoopKeys = [];
35445         var flowLoopTypes = [];
35446         var sharedFlowNodes = [];
35447         var sharedFlowTypes = [];
35448         var flowNodeReachable = [];
35449         var potentialThisCollisions = [];
35450         var potentialNewTargetCollisions = [];
35451         var potentialWeakMapCollisions = [];
35452         var awaitedTypeStack = [];
35453         var diagnostics = ts.createDiagnosticCollection();
35454         var suggestionDiagnostics = ts.createDiagnosticCollection();
35455         var typeofTypesByName = ts.createMapFromTemplate({
35456             string: stringType,
35457             number: numberType,
35458             bigint: bigintType,
35459             boolean: booleanType,
35460             symbol: esSymbolType,
35461             undefined: undefinedType
35462         });
35463         var typeofType = createTypeofType();
35464         var _jsxNamespace;
35465         var _jsxFactoryEntity;
35466         var outofbandVarianceMarkerHandler;
35467         var subtypeRelation = ts.createMap();
35468         var strictSubtypeRelation = ts.createMap();
35469         var assignableRelation = ts.createMap();
35470         var comparableRelation = ts.createMap();
35471         var identityRelation = ts.createMap();
35472         var enumRelation = ts.createMap();
35473         var builtinGlobals = ts.createSymbolTable();
35474         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35475         initializeTypeChecker();
35476         return checker;
35477         function getJsxNamespace(location) {
35478             if (location) {
35479                 var file = ts.getSourceFileOfNode(location);
35480                 if (file) {
35481                     if (file.localJsxNamespace) {
35482                         return file.localJsxNamespace;
35483                     }
35484                     var jsxPragma = file.pragmas.get("jsx");
35485                     if (jsxPragma) {
35486                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35487                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35488                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35489                         if (file.localJsxFactory) {
35490                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35491                         }
35492                     }
35493                 }
35494             }
35495             if (!_jsxNamespace) {
35496                 _jsxNamespace = "React";
35497                 if (compilerOptions.jsxFactory) {
35498                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35499                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35500                     if (_jsxFactoryEntity) {
35501                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35502                     }
35503                 }
35504                 else if (compilerOptions.reactNamespace) {
35505                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35506                 }
35507             }
35508             if (!_jsxFactoryEntity) {
35509                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35510             }
35511             return _jsxNamespace;
35512             function markAsSynthetic(node) {
35513                 node.pos = -1;
35514                 node.end = -1;
35515                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35516             }
35517         }
35518         function getEmitResolver(sourceFile, cancellationToken) {
35519             // Ensure we have all the type information in place for this file so that all the
35520             // emitter questions of this resolver will return the right information.
35521             getDiagnostics(sourceFile, cancellationToken);
35522             return emitResolver;
35523         }
35524         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35525             var diagnostic = location
35526                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35527                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35528             var existing = diagnostics.lookup(diagnostic);
35529             if (existing) {
35530                 return existing;
35531             }
35532             else {
35533                 diagnostics.add(diagnostic);
35534                 return diagnostic;
35535             }
35536         }
35537         function error(location, message, arg0, arg1, arg2, arg3) {
35538             var diagnostic = location
35539                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35540                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35541             diagnostics.add(diagnostic);
35542             return diagnostic;
35543         }
35544         function addErrorOrSuggestion(isError, diagnostic) {
35545             if (isError) {
35546                 diagnostics.add(diagnostic);
35547             }
35548             else {
35549                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35550             }
35551         }
35552         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35553             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35554         }
35555         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35556             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35557             if (maybeMissingAwait) {
35558                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35559                 ts.addRelatedInfo(diagnostic, related);
35560             }
35561             return diagnostic;
35562         }
35563         function createSymbol(flags, name, checkFlags) {
35564             symbolCount++;
35565             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35566             symbol.checkFlags = checkFlags || 0;
35567             return symbol;
35568         }
35569         function getExcludedSymbolFlags(flags) {
35570             var result = 0;
35571             if (flags & 2 /* BlockScopedVariable */)
35572                 result |= 111551 /* BlockScopedVariableExcludes */;
35573             if (flags & 1 /* FunctionScopedVariable */)
35574                 result |= 111550 /* FunctionScopedVariableExcludes */;
35575             if (flags & 4 /* Property */)
35576                 result |= 0 /* PropertyExcludes */;
35577             if (flags & 8 /* EnumMember */)
35578                 result |= 900095 /* EnumMemberExcludes */;
35579             if (flags & 16 /* Function */)
35580                 result |= 110991 /* FunctionExcludes */;
35581             if (flags & 32 /* Class */)
35582                 result |= 899503 /* ClassExcludes */;
35583             if (flags & 64 /* Interface */)
35584                 result |= 788872 /* InterfaceExcludes */;
35585             if (flags & 256 /* RegularEnum */)
35586                 result |= 899327 /* RegularEnumExcludes */;
35587             if (flags & 128 /* ConstEnum */)
35588                 result |= 899967 /* ConstEnumExcludes */;
35589             if (flags & 512 /* ValueModule */)
35590                 result |= 110735 /* ValueModuleExcludes */;
35591             if (flags & 8192 /* Method */)
35592                 result |= 103359 /* MethodExcludes */;
35593             if (flags & 32768 /* GetAccessor */)
35594                 result |= 46015 /* GetAccessorExcludes */;
35595             if (flags & 65536 /* SetAccessor */)
35596                 result |= 78783 /* SetAccessorExcludes */;
35597             if (flags & 262144 /* TypeParameter */)
35598                 result |= 526824 /* TypeParameterExcludes */;
35599             if (flags & 524288 /* TypeAlias */)
35600                 result |= 788968 /* TypeAliasExcludes */;
35601             if (flags & 2097152 /* Alias */)
35602                 result |= 2097152 /* AliasExcludes */;
35603             return result;
35604         }
35605         function recordMergedSymbol(target, source) {
35606             if (!source.mergeId) {
35607                 source.mergeId = nextMergeId;
35608                 nextMergeId++;
35609             }
35610             mergedSymbols[source.mergeId] = target;
35611         }
35612         function cloneSymbol(symbol) {
35613             var result = createSymbol(symbol.flags, symbol.escapedName);
35614             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35615             result.parent = symbol.parent;
35616             if (symbol.valueDeclaration)
35617                 result.valueDeclaration = symbol.valueDeclaration;
35618             if (symbol.constEnumOnlyModule)
35619                 result.constEnumOnlyModule = true;
35620             if (symbol.members)
35621                 result.members = ts.cloneMap(symbol.members);
35622             if (symbol.exports)
35623                 result.exports = ts.cloneMap(symbol.exports);
35624             recordMergedSymbol(result, symbol);
35625             return result;
35626         }
35627         /**
35628          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35629          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35630          */
35631         function mergeSymbol(target, source, unidirectional) {
35632             if (unidirectional === void 0) { unidirectional = false; }
35633             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35634                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35635                 if (source === target) {
35636                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35637                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35638                     return target;
35639                 }
35640                 if (!(target.flags & 33554432 /* Transient */)) {
35641                     var resolvedTarget = resolveSymbol(target);
35642                     if (resolvedTarget === unknownSymbol) {
35643                         return source;
35644                     }
35645                     target = cloneSymbol(resolvedTarget);
35646                 }
35647                 // Javascript static-property-assignment declarations always merge, even though they are also values
35648                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35649                     // reset flag when merging instantiated module into value module that has only const enums
35650                     target.constEnumOnlyModule = false;
35651                 }
35652                 target.flags |= source.flags;
35653                 if (source.valueDeclaration) {
35654                     ts.setValueDeclaration(target, source.valueDeclaration);
35655                 }
35656                 ts.addRange(target.declarations, source.declarations);
35657                 if (source.members) {
35658                     if (!target.members)
35659                         target.members = ts.createSymbolTable();
35660                     mergeSymbolTable(target.members, source.members, unidirectional);
35661                 }
35662                 if (source.exports) {
35663                     if (!target.exports)
35664                         target.exports = ts.createSymbolTable();
35665                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35666                 }
35667                 if (!unidirectional) {
35668                     recordMergedSymbol(target, source);
35669                 }
35670             }
35671             else if (target.flags & 1024 /* NamespaceModule */) {
35672                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35673                 // as we will already report a "Declaration name conflicts..." error, and this error
35674                 // won't make much sense.
35675                 if (target !== globalThisSymbol) {
35676                     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));
35677                 }
35678             }
35679             else { // error
35680                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35681                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35682                 var message = isEitherEnum
35683                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35684                     : isEitherBlockScoped_1
35685                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35686                         : ts.Diagnostics.Duplicate_identifier_0;
35687                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35688                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35689                 var symbolName_1 = symbolToString(source);
35690                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35691                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35692                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35693                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35694                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35695                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35696                     });
35697                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35698                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35699                     });
35700                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35701                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35702                 }
35703                 else {
35704                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35705                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35706                 }
35707             }
35708             return target;
35709             function addDuplicateLocations(locs, symbol) {
35710                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35711                     var decl = _a[_i];
35712                     ts.pushIfUnique(locs, decl);
35713                 }
35714             }
35715         }
35716         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35717             ts.forEach(target.declarations, function (node) {
35718                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35719             });
35720         }
35721         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35722             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35723             var err = lookupOrIssueError(errorNode, message, symbolName);
35724             var _loop_6 = function (relatedNode) {
35725                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35726                 if (adjustedNode === errorNode)
35727                     return "continue";
35728                 err.relatedInformation = err.relatedInformation || [];
35729                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35730                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35731                 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 */; }))
35732                     return "continue";
35733                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35734             };
35735             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35736                 var relatedNode = _a[_i];
35737                 _loop_6(relatedNode);
35738             }
35739         }
35740         function combineSymbolTables(first, second) {
35741             if (!ts.hasEntries(first))
35742                 return second;
35743             if (!ts.hasEntries(second))
35744                 return first;
35745             var combined = ts.createSymbolTable();
35746             mergeSymbolTable(combined, first);
35747             mergeSymbolTable(combined, second);
35748             return combined;
35749         }
35750         function mergeSymbolTable(target, source, unidirectional) {
35751             if (unidirectional === void 0) { unidirectional = false; }
35752             source.forEach(function (sourceSymbol, id) {
35753                 var targetSymbol = target.get(id);
35754                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35755             });
35756         }
35757         function mergeModuleAugmentation(moduleName) {
35758             var _a, _b;
35759             var moduleAugmentation = moduleName.parent;
35760             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35761                 // this is a combined symbol for multiple augmentations within the same file.
35762                 // its symbol already has accumulated information for all declarations
35763                 // so we need to add it just once - do the work only for first declaration
35764                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35765                 return;
35766             }
35767             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35768                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35769             }
35770             else {
35771                 // find a module that about to be augmented
35772                 // do not validate names of augmentations that are defined in ambient context
35773                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35774                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35775                     : undefined;
35776                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35777                 if (!mainModule_1) {
35778                     return;
35779                 }
35780                 // obtain item referenced by 'export='
35781                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35782                 if (mainModule_1.flags & 1920 /* Namespace */) {
35783                     // If we're merging an augmentation to a pattern ambient module, we want to
35784                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35785                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35786                     // all the exports both from the pattern and from the augmentation, but
35787                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35788                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35789                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35790                         if (!patternAmbientModuleAugmentations) {
35791                             patternAmbientModuleAugmentations = ts.createMap();
35792                         }
35793                         // moduleName will be a StringLiteral since this is not `declare global`.
35794                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35795                     }
35796                     else {
35797                         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)) {
35798                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35799                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35800                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35801                                 var _d = _c[_i], key = _d[0], value = _d[1];
35802                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35803                                     mergeSymbol(resolvedExports.get(key), value);
35804                                 }
35805                             }
35806                         }
35807                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35808                     }
35809                 }
35810                 else {
35811                     // moduleName will be a StringLiteral since this is not `declare global`.
35812                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35813                 }
35814             }
35815         }
35816         function addToSymbolTable(target, source, message) {
35817             source.forEach(function (sourceSymbol, id) {
35818                 var targetSymbol = target.get(id);
35819                 if (targetSymbol) {
35820                     // Error on redeclarations
35821                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35822                 }
35823                 else {
35824                     target.set(id, sourceSymbol);
35825                 }
35826             });
35827             function addDeclarationDiagnostic(id, message) {
35828                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35829             }
35830         }
35831         function getSymbolLinks(symbol) {
35832             if (symbol.flags & 33554432 /* Transient */)
35833                 return symbol;
35834             var id = getSymbolId(symbol);
35835             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35836         }
35837         function getNodeLinks(node) {
35838             var nodeId = getNodeId(node);
35839             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
35840         }
35841         function isGlobalSourceFile(node) {
35842             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
35843         }
35844         function getSymbol(symbols, name, meaning) {
35845             if (meaning) {
35846                 var symbol = getMergedSymbol(symbols.get(name));
35847                 if (symbol) {
35848                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
35849                     if (symbol.flags & meaning) {
35850                         return symbol;
35851                     }
35852                     if (symbol.flags & 2097152 /* Alias */) {
35853                         var target = resolveAlias(symbol);
35854                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
35855                         if (target === unknownSymbol || target.flags & meaning) {
35856                             return symbol;
35857                         }
35858                     }
35859                 }
35860             }
35861             // return undefined if we can't find a symbol.
35862         }
35863         /**
35864          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
35865          * @param parameter a parameterDeclaration node
35866          * @param parameterName a name of the parameter to get the symbols for.
35867          * @return a tuple of two symbols
35868          */
35869         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
35870             var constructorDeclaration = parameter.parent;
35871             var classDeclaration = parameter.parent.parent;
35872             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
35873             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
35874             if (parameterSymbol && propertySymbol) {
35875                 return [parameterSymbol, propertySymbol];
35876             }
35877             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
35878         }
35879         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
35880             var declarationFile = ts.getSourceFileOfNode(declaration);
35881             var useFile = ts.getSourceFileOfNode(usage);
35882             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
35883             if (declarationFile !== useFile) {
35884                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
35885                     (!compilerOptions.outFile && !compilerOptions.out) ||
35886                     isInTypeQuery(usage) ||
35887                     declaration.flags & 8388608 /* Ambient */) {
35888                     // nodes are in different files and order cannot be determined
35889                     return true;
35890                 }
35891                 // declaration is after usage
35892                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
35893                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35894                     return true;
35895                 }
35896                 var sourceFiles = host.getSourceFiles();
35897                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
35898             }
35899             if (declaration.pos <= usage.pos) {
35900                 // declaration is before usage
35901                 if (declaration.kind === 191 /* BindingElement */) {
35902                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
35903                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
35904                     if (errorBindingElement) {
35905                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
35906                             declaration.pos < errorBindingElement.pos;
35907                     }
35908                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
35909                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
35910                 }
35911                 else if (declaration.kind === 242 /* VariableDeclaration */) {
35912                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
35913                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
35914                 }
35915                 else if (ts.isClassDeclaration(declaration)) {
35916                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
35917                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
35918                 }
35919                 else if (ts.isPropertyDeclaration(declaration)) {
35920                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
35921                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
35922                 }
35923                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
35924                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
35925                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35926                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
35927                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
35928                 }
35929                 return true;
35930             }
35931             // declaration is after usage, but it can still be legal if usage is deferred:
35932             // 1. inside an export specifier
35933             // 2. inside a function
35934             // 3. inside an instance property initializer, a reference to a non-instance property
35935             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
35936             // 4. inside a static property initializer, a reference to a static method in the same class
35937             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
35938             // or if usage is in a type context:
35939             // 1. inside a type query (typeof in type position)
35940             // 2. inside a jsdoc comment
35941             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
35942                 // export specifiers do not use the variable, they only make it available for use
35943                 return true;
35944             }
35945             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
35946             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
35947                 return true;
35948             }
35949             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
35950                 return true;
35951             }
35952             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35953                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35954                     && ts.getContainingClass(declaration)
35955                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
35956                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
35957                 }
35958                 else {
35959                     return true;
35960                 }
35961             }
35962             return false;
35963             function usageInTypeDeclaration() {
35964                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
35965             }
35966             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
35967                 switch (declaration.parent.parent.kind) {
35968                     case 225 /* VariableStatement */:
35969                     case 230 /* ForStatement */:
35970                     case 232 /* ForOfStatement */:
35971                         // variable statement/for/for-of statement case,
35972                         // use site should not be inside variable declaration (initializer of declaration or binding element)
35973                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
35974                             return true;
35975                         }
35976                         break;
35977                 }
35978                 // ForIn/ForOf case - use site should not be used in expression part
35979                 var grandparent = declaration.parent.parent;
35980                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
35981             }
35982             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
35983                 return !!ts.findAncestor(usage, function (current) {
35984                     if (current === declContainer) {
35985                         return "quit";
35986                     }
35987                     if (ts.isFunctionLike(current)) {
35988                         return true;
35989                     }
35990                     var initializerOfProperty = current.parent &&
35991                         current.parent.kind === 159 /* PropertyDeclaration */ &&
35992                         current.parent.initializer === current;
35993                     if (initializerOfProperty) {
35994                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
35995                             if (declaration.kind === 161 /* MethodDeclaration */) {
35996                                 return true;
35997                             }
35998                         }
35999                         else {
36000                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36001                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36002                                 return true;
36003                             }
36004                         }
36005                     }
36006                     return false;
36007                 });
36008             }
36009             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36010             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36011                 // always legal if usage is after declaration
36012                 if (usage.end > declaration.end) {
36013                     return false;
36014                 }
36015                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36016                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36017                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36018                     if (node === declaration) {
36019                         return "quit";
36020                     }
36021                     switch (node.kind) {
36022                         case 202 /* ArrowFunction */:
36023                             return true;
36024                         case 159 /* PropertyDeclaration */:
36025                             // even when stopping at any property declaration, they need to come from the same class
36026                             return stopAtAnyPropertyDeclaration &&
36027                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36028                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36029                                 ? "quit" : true;
36030                         case 223 /* Block */:
36031                             switch (node.parent.kind) {
36032                                 case 163 /* GetAccessor */:
36033                                 case 161 /* MethodDeclaration */:
36034                                 case 164 /* SetAccessor */:
36035                                     return true;
36036                                 default:
36037                                     return false;
36038                             }
36039                         default:
36040                             return false;
36041                     }
36042                 });
36043                 return ancestorChangingReferenceScope === undefined;
36044             }
36045         }
36046         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36047             var target = ts.getEmitScriptTarget(compilerOptions);
36048             var functionLocation = location;
36049             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36050                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36051                 // - static field in a class expression
36052                 // - optional chaining pre-es2020
36053                 // - nullish coalesce pre-es2020
36054                 // - spread assignment in binding pattern pre-es2017
36055                 if (target >= 2 /* ES2015 */) {
36056                     var links = getNodeLinks(functionLocation);
36057                     if (links.declarationRequiresScopeChange === undefined) {
36058                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36059                     }
36060                     return !links.declarationRequiresScopeChange;
36061                 }
36062             }
36063             return false;
36064             function requiresScopeChange(node) {
36065                 return requiresScopeChangeWorker(node.name)
36066                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36067             }
36068             function requiresScopeChangeWorker(node) {
36069                 switch (node.kind) {
36070                     case 202 /* ArrowFunction */:
36071                     case 201 /* FunctionExpression */:
36072                     case 244 /* FunctionDeclaration */:
36073                     case 162 /* Constructor */:
36074                         // do not descend into these
36075                         return false;
36076                     case 161 /* MethodDeclaration */:
36077                     case 163 /* GetAccessor */:
36078                     case 164 /* SetAccessor */:
36079                     case 281 /* PropertyAssignment */:
36080                         return requiresScopeChangeWorker(node.name);
36081                     case 159 /* PropertyDeclaration */:
36082                         // static properties in classes introduce temporary variables
36083                         if (ts.hasStaticModifier(node)) {
36084                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36085                         }
36086                         return requiresScopeChangeWorker(node.name);
36087                     default:
36088                         // null coalesce and optional chain pre-es2020 produce temporary variables
36089                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36090                             return target < 7 /* ES2020 */;
36091                         }
36092                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36093                             return target < 4 /* ES2017 */;
36094                         }
36095                         if (ts.isTypeNode(node))
36096                             return false;
36097                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36098                 }
36099             }
36100         }
36101         /**
36102          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36103          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36104          * the given name can be found.
36105          *
36106          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36107          */
36108         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36109             if (excludeGlobals === void 0) { excludeGlobals = false; }
36110             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36111         }
36112         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36113             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36114             var result;
36115             var lastLocation;
36116             var lastSelfReferenceLocation;
36117             var propertyWithInvalidInitializer;
36118             var associatedDeclarationForContainingInitializerOrBindingName;
36119             var withinDeferredContext = false;
36120             var errorLocation = location;
36121             var grandparent;
36122             var isInExternalModule = false;
36123             loop: while (location) {
36124                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36125                 if (location.locals && !isGlobalSourceFile(location)) {
36126                     if (result = lookup(location.locals, name, meaning)) {
36127                         var useResult = true;
36128                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36129                             // symbol lookup restrictions for function-like declarations
36130                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36131                             //   list and return type. However, local types are only in scope in the function body.
36132                             // - parameters are only in the scope of function body
36133                             // This restriction does not apply to JSDoc comment types because they are parented
36134                             // at a higher level than type parameters would normally be
36135                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36136                                 useResult = result.flags & 262144 /* TypeParameter */
36137                                     // type parameters are visible in parameter list, return type and type parameter list
36138                                     ? lastLocation === location.type ||
36139                                         lastLocation.kind === 156 /* Parameter */ ||
36140                                         lastLocation.kind === 155 /* TypeParameter */
36141                                     // local types not visible outside the function body
36142                                     : false;
36143                             }
36144                             if (meaning & result.flags & 3 /* Variable */) {
36145                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36146                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36147                                     useResult = false;
36148                                 }
36149                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36150                                     // parameters are visible only inside function body, parameter list and return type
36151                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36152                                     // however it is detected separately when checking initializers of parameters
36153                                     // to make sure that they reference no variables declared after them.
36154                                     useResult =
36155                                         lastLocation.kind === 156 /* Parameter */ ||
36156                                             (lastLocation === location.type &&
36157                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36158                                 }
36159                             }
36160                         }
36161                         else if (location.kind === 180 /* ConditionalType */) {
36162                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36163                             // the true branch of the conditional type.
36164                             useResult = lastLocation === location.trueType;
36165                         }
36166                         if (useResult) {
36167                             break loop;
36168                         }
36169                         else {
36170                             result = undefined;
36171                         }
36172                     }
36173                 }
36174                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36175                 switch (location.kind) {
36176                     case 290 /* SourceFile */:
36177                         if (!ts.isExternalOrCommonJsModule(location))
36178                             break;
36179                         isInExternalModule = true;
36180                     // falls through
36181                     case 249 /* ModuleDeclaration */:
36182                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36183                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36184                             // It's an external module. First see if the module has an export default and if the local
36185                             // name of that export default matches.
36186                             if (result = moduleExports.get("default" /* Default */)) {
36187                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36188                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36189                                     break loop;
36190                                 }
36191                                 result = undefined;
36192                             }
36193                             // Because of module/namespace merging, a module's exports are in scope,
36194                             // yet we never want to treat an export specifier as putting a member in scope.
36195                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36196                             // Two things to note about this:
36197                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36198                             //        on an export specifier is that it might find the export specifier itself, and try to
36199                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36200                             //        a circular alias reference when it might not be.
36201                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36202                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36203                             //        which is not the desired behavior.
36204                             var moduleExport = moduleExports.get(name);
36205                             if (moduleExport &&
36206                                 moduleExport.flags === 2097152 /* Alias */ &&
36207                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36208                                 break;
36209                             }
36210                         }
36211                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36212                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36213                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36214                                 result = undefined;
36215                             }
36216                             else {
36217                                 break loop;
36218                             }
36219                         }
36220                         break;
36221                     case 248 /* EnumDeclaration */:
36222                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36223                             break loop;
36224                         }
36225                         break;
36226                     case 159 /* PropertyDeclaration */:
36227                         // TypeScript 1.0 spec (April 2014): 8.4.1
36228                         // Initializer expressions for instance member variables are evaluated in the scope
36229                         // of the class constructor body but are not permitted to reference parameters or
36230                         // local variables of the constructor. This effectively means that entities from outer scopes
36231                         // by the same name as a constructor parameter or local variable are inaccessible
36232                         // in initializer expressions for instance member variables.
36233                         if (!ts.hasModifier(location, 32 /* Static */)) {
36234                             var ctor = findConstructorDeclaration(location.parent);
36235                             if (ctor && ctor.locals) {
36236                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36237                                     // Remember the property node, it will be used later to report appropriate error
36238                                     propertyWithInvalidInitializer = location;
36239                                 }
36240                             }
36241                         }
36242                         break;
36243                     case 245 /* ClassDeclaration */:
36244                     case 214 /* ClassExpression */:
36245                     case 246 /* InterfaceDeclaration */:
36246                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36247                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36248                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36249                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36250                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36251                                 // ignore type parameters not declared in this container
36252                                 result = undefined;
36253                                 break;
36254                             }
36255                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36256                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36257                                 // The scope of a type parameter extends over the entire declaration with which the type
36258                                 // parameter list is associated, with the exception of static member declarations in classes.
36259                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36260                                 return undefined;
36261                             }
36262                             break loop;
36263                         }
36264                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36265                             var className = location.name;
36266                             if (className && name === className.escapedText) {
36267                                 result = location.symbol;
36268                                 break loop;
36269                             }
36270                         }
36271                         break;
36272                     case 216 /* ExpressionWithTypeArguments */:
36273                         // The type parameters of a class are not in scope in the base class expression.
36274                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36275                             var container = location.parent.parent;
36276                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36277                                 if (nameNotFoundMessage) {
36278                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36279                                 }
36280                                 return undefined;
36281                             }
36282                         }
36283                         break;
36284                     // It is not legal to reference a class's own type parameters from a computed property name that
36285                     // belongs to the class. For example:
36286                     //
36287                     //   function foo<T>() { return '' }
36288                     //   class C<T> { // <-- Class's own type parameter T
36289                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36290                     //   }
36291                     //
36292                     case 154 /* ComputedPropertyName */:
36293                         grandparent = location.parent.parent;
36294                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36295                             // A reference to this grandparent's type parameters would be an error
36296                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36297                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36298                                 return undefined;
36299                             }
36300                         }
36301                         break;
36302                     case 202 /* ArrowFunction */:
36303                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36304                         // for lower compile targets the resolved symbol is used to emit an error
36305                         if (compilerOptions.target >= 2 /* ES2015 */) {
36306                             break;
36307                         }
36308                     // falls through
36309                     case 161 /* MethodDeclaration */:
36310                     case 162 /* Constructor */:
36311                     case 163 /* GetAccessor */:
36312                     case 164 /* SetAccessor */:
36313                     case 244 /* FunctionDeclaration */:
36314                         if (meaning & 3 /* Variable */ && name === "arguments") {
36315                             result = argumentsSymbol;
36316                             break loop;
36317                         }
36318                         break;
36319                     case 201 /* FunctionExpression */:
36320                         if (meaning & 3 /* Variable */ && name === "arguments") {
36321                             result = argumentsSymbol;
36322                             break loop;
36323                         }
36324                         if (meaning & 16 /* Function */) {
36325                             var functionName = location.name;
36326                             if (functionName && name === functionName.escapedText) {
36327                                 result = location.symbol;
36328                                 break loop;
36329                             }
36330                         }
36331                         break;
36332                     case 157 /* Decorator */:
36333                         // Decorators are resolved at the class declaration. Resolving at the parameter
36334                         // or member would result in looking up locals in the method.
36335                         //
36336                         //   function y() {}
36337                         //   class C {
36338                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36339                         //   }
36340                         //
36341                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36342                             location = location.parent;
36343                         }
36344                         //
36345                         //   function y() {}
36346                         //   class C {
36347                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36348                         //   }
36349                         //
36350                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36351                         //
36352                         //   type T = number;
36353                         //   declare function y(x: T): any;
36354                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36355                         //   class C<T> {}
36356                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36357                             location = location.parent;
36358                         }
36359                         break;
36360                     case 322 /* JSDocTypedefTag */:
36361                     case 315 /* JSDocCallbackTag */:
36362                     case 316 /* JSDocEnumTag */:
36363                         // js type aliases do not resolve names from their host, so skip past it
36364                         location = ts.getJSDocHost(location);
36365                         break;
36366                     case 156 /* Parameter */:
36367                         if (lastLocation && (lastLocation === location.initializer ||
36368                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36369                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36370                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36371                             }
36372                         }
36373                         break;
36374                     case 191 /* BindingElement */:
36375                         if (lastLocation && (lastLocation === location.initializer ||
36376                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36377                             var root = ts.getRootDeclaration(location);
36378                             if (root.kind === 156 /* Parameter */) {
36379                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36380                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36381                                 }
36382                             }
36383                         }
36384                         break;
36385                 }
36386                 if (isSelfReferenceLocation(location)) {
36387                     lastSelfReferenceLocation = location;
36388                 }
36389                 lastLocation = location;
36390                 location = location.parent;
36391             }
36392             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36393             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36394             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36395             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36396                 result.isReferenced |= meaning;
36397             }
36398             if (!result) {
36399                 if (lastLocation) {
36400                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36401                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36402                         return lastLocation.symbol;
36403                     }
36404                 }
36405                 if (!excludeGlobals) {
36406                     result = lookup(globals, name, meaning);
36407                 }
36408             }
36409             if (!result) {
36410                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36411                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36412                         return requireSymbol;
36413                     }
36414                 }
36415             }
36416             if (!result) {
36417                 if (nameNotFoundMessage) {
36418                     if (!errorLocation ||
36419                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36420                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36421                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36422                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36423                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36424                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36425                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36426                         var suggestion = void 0;
36427                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36428                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36429                             if (suggestion) {
36430                                 var suggestionName = symbolToString(suggestion);
36431                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36432                                 if (suggestion.valueDeclaration) {
36433                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36434                                 }
36435                             }
36436                         }
36437                         if (!suggestion) {
36438                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36439                         }
36440                         suggestionCount++;
36441                     }
36442                 }
36443                 return undefined;
36444             }
36445             // Perform extra checks only if error reporting was requested
36446             if (nameNotFoundMessage) {
36447                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36448                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36449                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36450                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36451                     var propertyName = propertyWithInvalidInitializer.name;
36452                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36453                     return undefined;
36454                 }
36455                 // Only check for block-scoped variable if we have an error location and are looking for the
36456                 // name with variable meaning
36457                 //      For example,
36458                 //          declare module foo {
36459                 //              interface bar {}
36460                 //          }
36461                 //      const foo/*1*/: foo/*2*/.bar;
36462                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36463                 // block-scoped variable and namespace module. However, only when we
36464                 // try to resolve name in /*1*/ which is used in variable position,
36465                 // we want to check for block-scoped
36466                 if (errorLocation &&
36467                     (meaning & 2 /* BlockScopedVariable */ ||
36468                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36469                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36470                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36471                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36472                     }
36473                 }
36474                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36475                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36476                     var merged = getMergedSymbol(result);
36477                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36478                         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));
36479                     }
36480                 }
36481                 // 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
36482                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36483                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36484                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36485                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36486                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36487                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36488                     }
36489                     // And it cannot refer to any declarations which come after it
36490                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36491                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36492                     }
36493                 }
36494                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36495                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36496                 }
36497             }
36498             return result;
36499         }
36500         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36501             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36502                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36503                 if (typeOnlyDeclaration) {
36504                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36505                     var message = isExport
36506                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36507                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36508                     var relatedMessage = isExport
36509                         ? ts.Diagnostics._0_was_exported_here
36510                         : ts.Diagnostics._0_was_imported_here;
36511                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36512                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36513                 }
36514             }
36515         }
36516         function getIsDeferredContext(location, lastLocation) {
36517             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36518                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36519                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36520                     (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
36521             }
36522             if (lastLocation && lastLocation === location.name) {
36523                 return false;
36524             }
36525             // generator functions and async functions are not inlined in control flow when immediately invoked
36526             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36527                 return true;
36528             }
36529             return !ts.getImmediatelyInvokedFunctionExpression(location);
36530         }
36531         function isSelfReferenceLocation(node) {
36532             switch (node.kind) {
36533                 case 244 /* FunctionDeclaration */:
36534                 case 245 /* ClassDeclaration */:
36535                 case 246 /* InterfaceDeclaration */:
36536                 case 248 /* EnumDeclaration */:
36537                 case 247 /* TypeAliasDeclaration */:
36538                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36539                     return true;
36540                 default:
36541                     return false;
36542             }
36543         }
36544         function diagnosticName(nameArg) {
36545             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36546         }
36547         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36548             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36549                 var decl = _a[_i];
36550                 if (decl.kind === 155 /* TypeParameter */) {
36551                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36552                     if (parent === container) {
36553                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36554                     }
36555                 }
36556             }
36557             return false;
36558         }
36559         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36560             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36561                 return false;
36562             }
36563             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36564             var location = container;
36565             while (location) {
36566                 if (ts.isClassLike(location.parent)) {
36567                     var classSymbol = getSymbolOfNode(location.parent);
36568                     if (!classSymbol) {
36569                         break;
36570                     }
36571                     // Check to see if a static member exists.
36572                     var constructorType = getTypeOfSymbol(classSymbol);
36573                     if (getPropertyOfType(constructorType, name)) {
36574                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36575                         return true;
36576                     }
36577                     // No static member is present.
36578                     // Check if we're in an instance method and look for a relevant instance member.
36579                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36580                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36581                         if (getPropertyOfType(instanceType, name)) {
36582                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36583                             return true;
36584                         }
36585                     }
36586                 }
36587                 location = location.parent;
36588             }
36589             return false;
36590         }
36591         function checkAndReportErrorForExtendingInterface(errorLocation) {
36592             var expression = getEntityNameForExtendingInterface(errorLocation);
36593             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36594                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36595                 return true;
36596             }
36597             return false;
36598         }
36599         /**
36600          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36601          * but returns undefined if that expression is not an EntityNameExpression.
36602          */
36603         function getEntityNameForExtendingInterface(node) {
36604             switch (node.kind) {
36605                 case 75 /* Identifier */:
36606                 case 194 /* PropertyAccessExpression */:
36607                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36608                 case 216 /* ExpressionWithTypeArguments */:
36609                     if (ts.isEntityNameExpression(node.expression)) {
36610                         return node.expression;
36611                     }
36612                 // falls through
36613                 default:
36614                     return undefined;
36615             }
36616         }
36617         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36618             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36619             if (meaning === namespaceMeaning) {
36620                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36621                 var parent = errorLocation.parent;
36622                 if (symbol) {
36623                     if (ts.isQualifiedName(parent)) {
36624                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36625                         var propName = parent.right.escapedText;
36626                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36627                         if (propType) {
36628                             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));
36629                             return true;
36630                         }
36631                     }
36632                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36633                     return true;
36634                 }
36635             }
36636             return false;
36637         }
36638         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36639             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36640                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36641                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36642                     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));
36643                     return true;
36644                 }
36645             }
36646             return false;
36647         }
36648         function isPrimitiveTypeName(name) {
36649             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36650         }
36651         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36652             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36653                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36654                 return true;
36655             }
36656             return false;
36657         }
36658         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36659             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36660                 if (isPrimitiveTypeName(name)) {
36661                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36662                     return true;
36663                 }
36664                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36665                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36666                     var message = isES2015OrLaterConstructorName(name)
36667                         ? 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
36668                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36669                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36670                     return true;
36671                 }
36672             }
36673             return false;
36674         }
36675         function isES2015OrLaterConstructorName(n) {
36676             switch (n) {
36677                 case "Promise":
36678                 case "Symbol":
36679                 case "Map":
36680                 case "WeakMap":
36681                 case "Set":
36682                 case "WeakSet":
36683                     return true;
36684             }
36685             return false;
36686         }
36687         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36688             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36689                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36690                 if (symbol) {
36691                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36692                     return true;
36693                 }
36694             }
36695             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36696                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36697                 if (symbol) {
36698                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36699                     return true;
36700                 }
36701             }
36702             return false;
36703         }
36704         function checkResolvedBlockScopedVariable(result, errorLocation) {
36705             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36706             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36707                 // constructor functions aren't block scoped
36708                 return;
36709             }
36710             // Block-scoped variables cannot be used before their definition
36711             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36712             if (declaration === undefined)
36713                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36714             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36715                 var diagnosticMessage = void 0;
36716                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36717                 if (result.flags & 2 /* BlockScopedVariable */) {
36718                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36719                 }
36720                 else if (result.flags & 32 /* Class */) {
36721                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36722                 }
36723                 else if (result.flags & 256 /* RegularEnum */) {
36724                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36725                 }
36726                 else {
36727                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36728                     if (compilerOptions.preserveConstEnums) {
36729                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36730                     }
36731                 }
36732                 if (diagnosticMessage) {
36733                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36734                 }
36735             }
36736         }
36737         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36738          * If at any point current node is equal to 'parent' node - return true.
36739          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36740          */
36741         function isSameScopeDescendentOf(initial, parent, stopAt) {
36742             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36743         }
36744         function getAnyImportSyntax(node) {
36745             switch (node.kind) {
36746                 case 253 /* ImportEqualsDeclaration */:
36747                     return node;
36748                 case 255 /* ImportClause */:
36749                     return node.parent;
36750                 case 256 /* NamespaceImport */:
36751                     return node.parent.parent;
36752                 case 258 /* ImportSpecifier */:
36753                     return node.parent.parent.parent;
36754                 default:
36755                     return undefined;
36756             }
36757         }
36758         function getDeclarationOfAliasSymbol(symbol) {
36759             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36760         }
36761         /**
36762          * An alias symbol is created by one of the following declarations:
36763          * import <symbol> = ...
36764          * import <symbol> from ...
36765          * import * as <symbol> from ...
36766          * import { x as <symbol> } from ...
36767          * export { x as <symbol> } from ...
36768          * export * as ns <symbol> from ...
36769          * export = <EntityNameExpression>
36770          * export default <EntityNameExpression>
36771          * module.exports = <EntityNameExpression>
36772          * {<Identifier>}
36773          * {name: <EntityNameExpression>}
36774          */
36775         function isAliasSymbolDeclaration(node) {
36776             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36777                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36778                 node.kind === 255 /* ImportClause */ && !!node.name ||
36779                 node.kind === 256 /* NamespaceImport */ ||
36780                 node.kind === 262 /* NamespaceExport */ ||
36781                 node.kind === 258 /* ImportSpecifier */ ||
36782                 node.kind === 263 /* ExportSpecifier */ ||
36783                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36784                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36785                 ts.isPropertyAccessExpression(node)
36786                     && ts.isBinaryExpression(node.parent)
36787                     && node.parent.left === node
36788                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36789                     && isAliasableOrJsExpression(node.parent.right) ||
36790                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36791                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36792         }
36793         function isAliasableOrJsExpression(e) {
36794             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36795         }
36796         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36797             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36798                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36799                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36800                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36801                 return resolved_4;
36802             }
36803             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36804             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36805             return resolved;
36806         }
36807         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36808             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36809                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36810                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36811                 var message = isExport
36812                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36813                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36814                 var relatedMessage = isExport
36815                     ? ts.Diagnostics._0_was_exported_here
36816                     : ts.Diagnostics._0_was_imported_here;
36817                 // Non-null assertion is safe because the optionality comes from ImportClause,
36818                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36819                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36820                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36821             }
36822         }
36823         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36824             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36825             if (exportValue) {
36826                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36827             }
36828             var exportSymbol = moduleSymbol.exports.get(name);
36829             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36830             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36831             return resolved;
36832         }
36833         function isSyntacticDefault(node) {
36834             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36835         }
36836         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36837             if (!allowSyntheticDefaultImports) {
36838                 return false;
36839             }
36840             // Declaration files (and ambient modules)
36841             if (!file || file.isDeclarationFile) {
36842                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
36843                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
36844                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
36845                     return false;
36846                 }
36847                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
36848                 // So we check a bit more,
36849                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
36850                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
36851                     // it definitely is a module and does not have a synthetic default
36852                     return false;
36853                 }
36854                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
36855                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
36856                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
36857                 return true;
36858             }
36859             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
36860             if (!ts.isSourceFileJS(file)) {
36861                 return hasExportAssignmentSymbol(moduleSymbol);
36862             }
36863             // 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
36864             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
36865         }
36866         function getTargetOfImportClause(node, dontResolveAlias) {
36867             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
36868             if (moduleSymbol) {
36869                 var exportDefaultSymbol = void 0;
36870                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36871                     exportDefaultSymbol = moduleSymbol;
36872                 }
36873                 else {
36874                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
36875                 }
36876                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
36877                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
36878                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
36879                     if (hasExportAssignmentSymbol(moduleSymbol)) {
36880                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
36881                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
36882                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
36883                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
36884                         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));
36885                     }
36886                     else {
36887                         reportNonDefaultExport(moduleSymbol, node);
36888                     }
36889                 }
36890                 else if (hasSyntheticDefault) {
36891                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
36892                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
36893                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
36894                     return resolved;
36895                 }
36896                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
36897                 return exportDefaultSymbol;
36898             }
36899         }
36900         function reportNonDefaultExport(moduleSymbol, node) {
36901             var _a, _b;
36902             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
36903                 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));
36904             }
36905             else {
36906                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
36907                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
36908                 if (exportStar) {
36909                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
36910                         var _a, _b;
36911                         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 */)));
36912                     });
36913                     if (defaultExport) {
36914                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
36915                     }
36916                 }
36917             }
36918         }
36919         function getTargetOfNamespaceImport(node, dontResolveAlias) {
36920             var moduleSpecifier = node.parent.parent.moduleSpecifier;
36921             var immediate = resolveExternalModuleName(node, moduleSpecifier);
36922             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36923             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36924             return resolved;
36925         }
36926         function getTargetOfNamespaceExport(node, dontResolveAlias) {
36927             var moduleSpecifier = node.parent.moduleSpecifier;
36928             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
36929             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36930             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36931             return resolved;
36932         }
36933         // This function creates a synthetic symbol that combines the value side of one symbol with the
36934         // type/namespace side of another symbol. Consider this example:
36935         //
36936         //   declare module graphics {
36937         //       interface Point {
36938         //           x: number;
36939         //           y: number;
36940         //       }
36941         //   }
36942         //   declare var graphics: {
36943         //       Point: new (x: number, y: number) => graphics.Point;
36944         //   }
36945         //   declare module "graphics" {
36946         //       export = graphics;
36947         //   }
36948         //
36949         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
36950         // property with the type/namespace side interface 'Point'.
36951         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
36952             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
36953                 return unknownSymbol;
36954             }
36955             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
36956                 return valueSymbol;
36957             }
36958             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
36959             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
36960             result.parent = valueSymbol.parent || typeSymbol.parent;
36961             if (valueSymbol.valueDeclaration)
36962                 result.valueDeclaration = valueSymbol.valueDeclaration;
36963             if (typeSymbol.members)
36964                 result.members = ts.cloneMap(typeSymbol.members);
36965             if (valueSymbol.exports)
36966                 result.exports = ts.cloneMap(valueSymbol.exports);
36967             return result;
36968         }
36969         function getExportOfModule(symbol, specifier, dontResolveAlias) {
36970             var _a;
36971             if (symbol.flags & 1536 /* Module */) {
36972                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
36973                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
36974                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36975                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
36976                 return resolved;
36977             }
36978         }
36979         function getPropertyOfVariable(symbol, name) {
36980             if (symbol.flags & 3 /* Variable */) {
36981                 var typeAnnotation = symbol.valueDeclaration.type;
36982                 if (typeAnnotation) {
36983                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
36984                 }
36985             }
36986         }
36987         function getExternalModuleMember(node, specifier, dontResolveAlias) {
36988             var _a;
36989             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
36990             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
36991             var name = specifier.propertyName || specifier.name;
36992             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
36993             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
36994             if (targetSymbol) {
36995                 if (name.escapedText) {
36996                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36997                         return moduleSymbol;
36998                     }
36999                     var symbolFromVariable = void 0;
37000                     // First check if module was specified with "export=". If so, get the member from the resolved type
37001                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37002                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37003                     }
37004                     else {
37005                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37006                     }
37007                     // if symbolFromVariable is export - get its final target
37008                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37009                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37010                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37011                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37012                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37013                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37014                         }
37015                     }
37016                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37017                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37018                         symbolFromModule || symbolFromVariable;
37019                     if (!symbol) {
37020                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37021                         var declarationName = ts.declarationNameToString(name);
37022                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37023                         if (suggestion !== undefined) {
37024                             var suggestionName = symbolToString(suggestion);
37025                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37026                             if (suggestion.valueDeclaration) {
37027                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37028                             }
37029                         }
37030                         else {
37031                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37032                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37033                             }
37034                             else {
37035                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37036                             }
37037                         }
37038                     }
37039                     return symbol;
37040                 }
37041             }
37042         }
37043         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37044             var _a;
37045             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37046             var exports = moduleSymbol.exports;
37047             if (localSymbol) {
37048                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37049                 if (exportedEqualsSymbol) {
37050                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37051                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37052                 }
37053                 else {
37054                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37055                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37056                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37057                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37058                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37059                     })));
37060                 }
37061             }
37062             else {
37063                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37064             }
37065         }
37066         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37067             if (moduleKind >= ts.ModuleKind.ES2015) {
37068                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37069                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37070                 error(name, message, declarationName);
37071             }
37072             else {
37073                 if (ts.isInJSFile(node)) {
37074                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37075                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37076                     error(name, message, declarationName);
37077                 }
37078                 else {
37079                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37080                         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;
37081                     error(name, message, declarationName, declarationName, moduleName);
37082                 }
37083             }
37084         }
37085         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37086             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37087             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37088             return resolved;
37089         }
37090         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37091             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37092             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37093             return resolved;
37094         }
37095         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37096             var resolved = node.parent.parent.moduleSpecifier ?
37097                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37098                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37099             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37100             return resolved;
37101         }
37102         function getTargetOfExportAssignment(node, dontResolveAlias) {
37103             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37104             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37105             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37106             return resolved;
37107         }
37108         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37109             if (ts.isClassExpression(expression)) {
37110                 return checkExpressionCached(expression).symbol;
37111             }
37112             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37113                 return undefined;
37114             }
37115             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37116             if (aliasLike) {
37117                 return aliasLike;
37118             }
37119             checkExpressionCached(expression);
37120             return getNodeLinks(expression).resolvedSymbol;
37121         }
37122         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37123             var expression = node.initializer;
37124             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37125         }
37126         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37127             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37128                 return undefined;
37129             }
37130             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37131         }
37132         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37133             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37134             switch (node.kind) {
37135                 case 253 /* ImportEqualsDeclaration */:
37136                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37137                 case 255 /* ImportClause */:
37138                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37139                 case 256 /* NamespaceImport */:
37140                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37141                 case 262 /* NamespaceExport */:
37142                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37143                 case 258 /* ImportSpecifier */:
37144                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37145                 case 263 /* ExportSpecifier */:
37146                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37147                 case 259 /* ExportAssignment */:
37148                 case 209 /* BinaryExpression */:
37149                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37150                 case 252 /* NamespaceExportDeclaration */:
37151                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37152                 case 282 /* ShorthandPropertyAssignment */:
37153                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37154                 case 281 /* PropertyAssignment */:
37155                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37156                 case 194 /* PropertyAccessExpression */:
37157                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37158                 default:
37159                     return ts.Debug.fail();
37160             }
37161         }
37162         /**
37163          * Indicates that a symbol is an alias that does not merge with a local declaration.
37164          * OR Is a JSContainer which may merge an alias with a local declaration
37165          */
37166         function isNonLocalAlias(symbol, excludes) {
37167             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37168             if (!symbol)
37169                 return false;
37170             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37171         }
37172         function resolveSymbol(symbol, dontResolveAlias) {
37173             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37174         }
37175         function resolveAlias(symbol) {
37176             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37177             var links = getSymbolLinks(symbol);
37178             if (!links.target) {
37179                 links.target = resolvingSymbol;
37180                 var node = getDeclarationOfAliasSymbol(symbol);
37181                 if (!node)
37182                     return ts.Debug.fail();
37183                 var target = getTargetOfAliasDeclaration(node);
37184                 if (links.target === resolvingSymbol) {
37185                     links.target = target || unknownSymbol;
37186                 }
37187                 else {
37188                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37189                 }
37190             }
37191             else if (links.target === resolvingSymbol) {
37192                 links.target = unknownSymbol;
37193             }
37194             return links.target;
37195         }
37196         function tryResolveAlias(symbol) {
37197             var links = getSymbolLinks(symbol);
37198             if (links.target !== resolvingSymbol) {
37199                 return resolveAlias(symbol);
37200             }
37201             return undefined;
37202         }
37203         /**
37204          * Marks a symbol as type-only if its declaration is syntactically type-only.
37205          * If it is not itself marked type-only, but resolves to a type-only alias
37206          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37207          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37208          *
37209          * This function is called on each alias declaration that could be type-only or resolve to
37210          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37211          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37212          * and issue an error if so.
37213          *
37214          * @param aliasDeclaration The alias declaration not marked as type-only
37215          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37216          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37217          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37218          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37219          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37220          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37221          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37222          */
37223         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37224             if (!aliasDeclaration)
37225                 return false;
37226             // If the declaration itself is type-only, mark it and return.
37227             // No need to check what it resolves to.
37228             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37229             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37230                 var links_1 = getSymbolLinks(sourceSymbol);
37231                 links_1.typeOnlyDeclaration = aliasDeclaration;
37232                 return true;
37233             }
37234             var links = getSymbolLinks(sourceSymbol);
37235             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37236                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37237         }
37238         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37239             var _a, _b, _c;
37240             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37241                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37242                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37243                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37244             }
37245             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37246         }
37247         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37248         function getTypeOnlyAliasDeclaration(symbol) {
37249             if (!(symbol.flags & 2097152 /* Alias */)) {
37250                 return undefined;
37251             }
37252             var links = getSymbolLinks(symbol);
37253             return links.typeOnlyDeclaration || undefined;
37254         }
37255         function markExportAsReferenced(node) {
37256             var symbol = getSymbolOfNode(node);
37257             var target = resolveAlias(symbol);
37258             if (target) {
37259                 var markAlias = target === unknownSymbol ||
37260                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37261                 if (markAlias) {
37262                     markAliasSymbolAsReferenced(symbol);
37263                 }
37264             }
37265         }
37266         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37267         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37268         // the alias as an expression (which recursively takes us back here if the target references another alias).
37269         function markAliasSymbolAsReferenced(symbol) {
37270             var links = getSymbolLinks(symbol);
37271             if (!links.referenced) {
37272                 links.referenced = true;
37273                 var node = getDeclarationOfAliasSymbol(symbol);
37274                 if (!node)
37275                     return ts.Debug.fail();
37276                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37277                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37278                 // position.
37279                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37280                     var target = resolveSymbol(symbol);
37281                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37282                         // import foo = <symbol>
37283                         checkExpressionCached(node.moduleReference);
37284                     }
37285                 }
37286             }
37287         }
37288         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37289         // but their usage in value positions must be tracked to determine if the import can be type-only.
37290         function markConstEnumAliasAsReferenced(symbol) {
37291             var links = getSymbolLinks(symbol);
37292             if (!links.constEnumReferenced) {
37293                 links.constEnumReferenced = true;
37294             }
37295         }
37296         // This function is only for imports with entity names
37297         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37298             // There are three things we might try to look for. In the following examples,
37299             // the search term is enclosed in |...|:
37300             //
37301             //     import a = |b|; // Namespace
37302             //     import a = |b.c|; // Value, type, namespace
37303             //     import a = |b.c|.d; // Namespace
37304             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37305                 entityName = entityName.parent;
37306             }
37307             // Check for case 1 and 3 in the above example
37308             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37309                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37310             }
37311             else {
37312                 // Case 2 in above example
37313                 // entityName.kind could be a QualifiedName or a Missing identifier
37314                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37315                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37316             }
37317         }
37318         function getFullyQualifiedName(symbol, containingLocation) {
37319             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37320         }
37321         /**
37322          * Resolves a qualified name and any involved aliases.
37323          */
37324         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37325             if (ts.nodeIsMissing(name)) {
37326                 return undefined;
37327             }
37328             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37329             var symbol;
37330             if (name.kind === 75 /* Identifier */) {
37331                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37332                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37333                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37334                 if (!symbol) {
37335                     return getMergedSymbol(symbolFromJSPrototype);
37336                 }
37337             }
37338             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37339                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37340                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37341                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37342                 if (!namespace || ts.nodeIsMissing(right)) {
37343                     return undefined;
37344                 }
37345                 else if (namespace === unknownSymbol) {
37346                     return namespace;
37347                 }
37348                 if (ts.isInJSFile(name)) {
37349                     if (namespace.valueDeclaration &&
37350                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37351                         namespace.valueDeclaration.initializer &&
37352                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37353                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37354                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37355                         if (moduleSym) {
37356                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37357                             if (resolvedModuleSymbol) {
37358                                 namespace = resolvedModuleSymbol;
37359                             }
37360                         }
37361                     }
37362                 }
37363                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37364                 if (!symbol) {
37365                     if (!ignoreErrors) {
37366                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37367                     }
37368                     return undefined;
37369                 }
37370             }
37371             else {
37372                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37373             }
37374             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37375             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37376                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37377             }
37378             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37379         }
37380         /**
37381          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37382          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37383          * name resolution won't work either.
37384          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37385          */
37386         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37387             if (isJSDocTypeReference(name.parent)) {
37388                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37389                 if (secondaryLocation) {
37390                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37391                 }
37392             }
37393         }
37394         function getAssignmentDeclarationLocation(node) {
37395             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37396             if (typeAlias) {
37397                 return;
37398             }
37399             var host = ts.getJSDocHost(node);
37400             if (ts.isExpressionStatement(host) &&
37401                 ts.isBinaryExpression(host.expression) &&
37402                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37403                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37404                 var symbol = getSymbolOfNode(host.expression.left);
37405                 if (symbol) {
37406                     return getDeclarationOfJSPrototypeContainer(symbol);
37407                 }
37408             }
37409             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37410                 ts.isBinaryExpression(host.parent.parent) &&
37411                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37412                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37413                 var symbol = getSymbolOfNode(host.parent.parent.left);
37414                 if (symbol) {
37415                     return getDeclarationOfJSPrototypeContainer(symbol);
37416                 }
37417             }
37418             var sig = ts.getEffectiveJSDocHost(node);
37419             if (sig && ts.isFunctionLike(sig)) {
37420                 var symbol = getSymbolOfNode(sig);
37421                 return symbol && symbol.valueDeclaration;
37422             }
37423         }
37424         function getDeclarationOfJSPrototypeContainer(symbol) {
37425             var decl = symbol.parent.valueDeclaration;
37426             if (!decl) {
37427                 return undefined;
37428             }
37429             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37430                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37431                     undefined;
37432             return initializer || decl;
37433         }
37434         /**
37435          * Get the real symbol of a declaration with an expando initializer.
37436          *
37437          * Normally, declarations have an associated symbol, but when a declaration has an expando
37438          * initializer, the expando's symbol is the one that has all the members merged into it.
37439          */
37440         function getExpandoSymbol(symbol) {
37441             var decl = symbol.valueDeclaration;
37442             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37443                 return undefined;
37444             }
37445             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37446             if (init) {
37447                 var initSymbol = getSymbolOfNode(init);
37448                 if (initSymbol) {
37449                     return mergeJSSymbols(initSymbol, symbol);
37450                 }
37451             }
37452         }
37453         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37454             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37455         }
37456         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37457             if (isForAugmentation === void 0) { isForAugmentation = false; }
37458             return ts.isStringLiteralLike(moduleReferenceExpression)
37459                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37460                 : undefined;
37461         }
37462         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37463             if (isForAugmentation === void 0) { isForAugmentation = false; }
37464             if (ts.startsWith(moduleReference, "@types/")) {
37465                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37466                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37467                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37468             }
37469             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37470             if (ambientModule) {
37471                 return ambientModule;
37472             }
37473             var currentSourceFile = ts.getSourceFileOfNode(location);
37474             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37475             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37476             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37477             if (sourceFile) {
37478                 if (sourceFile.symbol) {
37479                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37480                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37481                     }
37482                     // merged symbol is module declaration symbol combined with all augmentations
37483                     return getMergedSymbol(sourceFile.symbol);
37484                 }
37485                 if (moduleNotFoundError) {
37486                     // report errors only if it was requested
37487                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37488                 }
37489                 return undefined;
37490             }
37491             if (patternAmbientModules) {
37492                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37493                 if (pattern) {
37494                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37495                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37496                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37497                     // from a.foo.
37498                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37499                     if (augmentation) {
37500                         return getMergedSymbol(augmentation);
37501                     }
37502                     return getMergedSymbol(pattern.symbol);
37503                 }
37504             }
37505             // May be an untyped module. If so, ignore resolutionDiagnostic.
37506             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) {
37507                 if (isForAugmentation) {
37508                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37509                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37510                 }
37511                 else {
37512                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37513                 }
37514                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37515                 return undefined;
37516             }
37517             if (moduleNotFoundError) {
37518                 // See if this was possibly a projectReference redirect
37519                 if (resolvedModule) {
37520                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37521                     if (redirect) {
37522                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37523                         return undefined;
37524                     }
37525                 }
37526                 if (resolutionDiagnostic) {
37527                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37528                 }
37529                 else {
37530                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37531                     if (tsExtension) {
37532                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37533                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37534                     }
37535                     else if (!compilerOptions.resolveJsonModule &&
37536                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37537                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37538                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37539                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37540                     }
37541                     else {
37542                         error(errorNode, moduleNotFoundError, moduleReference);
37543                     }
37544                 }
37545             }
37546             return undefined;
37547         }
37548         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37549             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37550             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37551                 ? typesPackageExists(packageId.name)
37552                     ? ts.chainDiagnosticMessages(
37553                     /*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))
37554                     : ts.chainDiagnosticMessages(
37555                     /*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))
37556                 : undefined;
37557             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));
37558         }
37559         function typesPackageExists(packageName) {
37560             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37561         }
37562         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37563             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37564                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37565                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37566                 return getMergedSymbol(exported) || moduleSymbol;
37567             }
37568             return undefined;
37569         }
37570         function getCommonJsExportEquals(exported, moduleSymbol) {
37571             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37572                 return exported;
37573             }
37574             var links = getSymbolLinks(exported);
37575             if (links.cjsExportMerged) {
37576                 return links.cjsExportMerged;
37577             }
37578             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37579             merged.flags = merged.flags | 512 /* ValueModule */;
37580             if (merged.exports === undefined) {
37581                 merged.exports = ts.createSymbolTable();
37582             }
37583             moduleSymbol.exports.forEach(function (s, name) {
37584                 if (name === "export=" /* ExportEquals */)
37585                     return;
37586                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37587             });
37588             getSymbolLinks(merged).cjsExportMerged = merged;
37589             return links.cjsExportMerged = merged;
37590         }
37591         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37592         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37593         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37594         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37595             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37596             if (!dontResolveAlias && symbol) {
37597                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37598                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37599                         ? "allowSyntheticDefaultImports"
37600                         : "esModuleInterop";
37601                     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);
37602                     return symbol;
37603                 }
37604                 if (compilerOptions.esModuleInterop) {
37605                     var referenceParent = referencingLocation.parent;
37606                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37607                         ts.isImportCall(referenceParent)) {
37608                         var type = getTypeOfSymbol(symbol);
37609                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37610                         if (!sigs || !sigs.length) {
37611                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37612                         }
37613                         if (sigs && sigs.length) {
37614                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37615                             // Create a new symbol which has the module's type less the call and construct signatures
37616                             var result = createSymbol(symbol.flags, symbol.escapedName);
37617                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37618                             result.parent = symbol.parent;
37619                             result.target = symbol;
37620                             result.originatingImport = referenceParent;
37621                             if (symbol.valueDeclaration)
37622                                 result.valueDeclaration = symbol.valueDeclaration;
37623                             if (symbol.constEnumOnlyModule)
37624                                 result.constEnumOnlyModule = true;
37625                             if (symbol.members)
37626                                 result.members = ts.cloneMap(symbol.members);
37627                             if (symbol.exports)
37628                                 result.exports = ts.cloneMap(symbol.exports);
37629                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37630                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37631                             return result;
37632                         }
37633                     }
37634                 }
37635             }
37636             return symbol;
37637         }
37638         function hasExportAssignmentSymbol(moduleSymbol) {
37639             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37640         }
37641         function getExportsOfModuleAsArray(moduleSymbol) {
37642             return symbolsToArray(getExportsOfModule(moduleSymbol));
37643         }
37644         function getExportsAndPropertiesOfModule(moduleSymbol) {
37645             var exports = getExportsOfModuleAsArray(moduleSymbol);
37646             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37647             if (exportEquals !== moduleSymbol) {
37648                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37649             }
37650             return exports;
37651         }
37652         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37653             var symbolTable = getExportsOfModule(moduleSymbol);
37654             if (symbolTable) {
37655                 return symbolTable.get(memberName);
37656             }
37657         }
37658         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37659             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37660             if (symbol) {
37661                 return symbol;
37662             }
37663             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37664             if (exportEquals === moduleSymbol) {
37665                 return undefined;
37666             }
37667             var type = getTypeOfSymbol(exportEquals);
37668             return type.flags & 131068 /* Primitive */ ||
37669                 ts.getObjectFlags(type) & 1 /* Class */ ||
37670                 isArrayOrTupleLikeType(type)
37671                 ? undefined
37672                 : getPropertyOfType(type, memberName);
37673         }
37674         function getExportsOfSymbol(symbol) {
37675             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37676                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37677                     symbol.exports || emptySymbols;
37678         }
37679         function getExportsOfModule(moduleSymbol) {
37680             var links = getSymbolLinks(moduleSymbol);
37681             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37682         }
37683         /**
37684          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37685          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37686          */
37687         function extendExportSymbols(target, source, lookupTable, exportNode) {
37688             if (!source)
37689                 return;
37690             source.forEach(function (sourceSymbol, id) {
37691                 if (id === "default" /* Default */)
37692                     return;
37693                 var targetSymbol = target.get(id);
37694                 if (!targetSymbol) {
37695                     target.set(id, sourceSymbol);
37696                     if (lookupTable && exportNode) {
37697                         lookupTable.set(id, {
37698                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37699                         });
37700                     }
37701                 }
37702                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37703                     var collisionTracker = lookupTable.get(id);
37704                     if (!collisionTracker.exportsWithDuplicate) {
37705                         collisionTracker.exportsWithDuplicate = [exportNode];
37706                     }
37707                     else {
37708                         collisionTracker.exportsWithDuplicate.push(exportNode);
37709                     }
37710                 }
37711             });
37712         }
37713         function getExportsOfModuleWorker(moduleSymbol) {
37714             var visitedSymbols = [];
37715             // A module defined by an 'export=' consists of one export that needs to be resolved
37716             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37717             return visit(moduleSymbol) || emptySymbols;
37718             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37719             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37720             function visit(symbol) {
37721                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37722                     return;
37723                 }
37724                 var symbols = ts.cloneMap(symbol.exports);
37725                 // All export * declarations are collected in an __export symbol by the binder
37726                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37727                 if (exportStars) {
37728                     var nestedSymbols = ts.createSymbolTable();
37729                     var lookupTable_1 = ts.createMap();
37730                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37731                         var node = _a[_i];
37732                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37733                         var exportedSymbols = visit(resolvedModule);
37734                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37735                     }
37736                     lookupTable_1.forEach(function (_a, id) {
37737                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37738                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37739                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37740                             return;
37741                         }
37742                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37743                             var node = exportsWithDuplicate_1[_i];
37744                             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)));
37745                         }
37746                     });
37747                     extendExportSymbols(symbols, nestedSymbols);
37748                 }
37749                 return symbols;
37750             }
37751         }
37752         function getMergedSymbol(symbol) {
37753             var merged;
37754             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37755         }
37756         function getSymbolOfNode(node) {
37757             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37758         }
37759         function getParentOfSymbol(symbol) {
37760             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37761         }
37762         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37763             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37764             var id = "" + getNodeId(containingFile);
37765             var links = getSymbolLinks(symbol);
37766             var results;
37767             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37768                 return results;
37769             }
37770             if (containingFile && containingFile.imports) {
37771                 // Try to make an import using an import already in the enclosing file, if possible
37772                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37773                     var importRef = _a[_i];
37774                     if (ts.nodeIsSynthesized(importRef))
37775                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37776                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37777                     if (!resolvedModule)
37778                         continue;
37779                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37780                     if (!ref)
37781                         continue;
37782                     results = ts.append(results, resolvedModule);
37783                 }
37784                 if (ts.length(results)) {
37785                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37786                     return results;
37787                 }
37788             }
37789             if (links.extendedContainers) {
37790                 return links.extendedContainers;
37791             }
37792             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37793             var otherFiles = host.getSourceFiles();
37794             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37795                 var file = otherFiles_1[_b];
37796                 if (!ts.isExternalModule(file))
37797                     continue;
37798                 var sym = getSymbolOfNode(file);
37799                 var ref = getAliasForSymbolInContainer(sym, symbol);
37800                 if (!ref)
37801                     continue;
37802                 results = ts.append(results, sym);
37803             }
37804             return links.extendedContainers = results || ts.emptyArray;
37805         }
37806         /**
37807          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37808          * is just its' `.parent`, but for locals, this value is `undefined`
37809          */
37810         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37811             var container = getParentOfSymbol(symbol);
37812             // Type parameters end up in the `members` lists but are not externally visible
37813             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37814                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37815                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37816                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37817                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37818                 }
37819                 var res = ts.append(additionalContainers, container);
37820                 return ts.concatenate(res, reexportContainers);
37821             }
37822             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37823                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37824                     return getSymbolOfNode(d.parent);
37825                 }
37826                 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)) {
37827                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37828                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37829                     }
37830                     checkExpressionCached(d.parent.left.expression);
37831                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37832                 }
37833             });
37834             if (!ts.length(candidates)) {
37835                 return undefined;
37836             }
37837             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
37838             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
37839                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
37840             }
37841         }
37842         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
37843             var fileSymbol = getExternalModuleContainer(d);
37844             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
37845             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
37846         }
37847         function getAliasForSymbolInContainer(container, symbol) {
37848             if (container === getParentOfSymbol(symbol)) {
37849                 // fast path, `symbol` is either already the alias or isn't aliased
37850                 return symbol;
37851             }
37852             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
37853             // the container itself as the alias for the symbol
37854             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
37855             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
37856                 return container;
37857             }
37858             var exports = getExportsOfSymbol(container);
37859             var quick = exports.get(symbol.escapedName);
37860             if (quick && getSymbolIfSameReference(quick, symbol)) {
37861                 return quick;
37862             }
37863             return ts.forEachEntry(exports, function (exported) {
37864                 if (getSymbolIfSameReference(exported, symbol)) {
37865                     return exported;
37866                 }
37867             });
37868         }
37869         /**
37870          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
37871          */
37872         function getSymbolIfSameReference(s1, s2) {
37873             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
37874                 return s1;
37875             }
37876         }
37877         function getExportSymbolOfValueSymbolIfExported(symbol) {
37878             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
37879         }
37880         function symbolIsValue(symbol) {
37881             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
37882         }
37883         function findConstructorDeclaration(node) {
37884             var members = node.members;
37885             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
37886                 var member = members_3[_i];
37887                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
37888                     return member;
37889                 }
37890             }
37891         }
37892         function createType(flags) {
37893             var result = new Type(checker, flags);
37894             typeCount++;
37895             result.id = typeCount;
37896             return result;
37897         }
37898         function createIntrinsicType(kind, intrinsicName, objectFlags) {
37899             if (objectFlags === void 0) { objectFlags = 0; }
37900             var type = createType(kind);
37901             type.intrinsicName = intrinsicName;
37902             type.objectFlags = objectFlags;
37903             return type;
37904         }
37905         function createBooleanType(trueFalseTypes) {
37906             var type = getUnionType(trueFalseTypes);
37907             type.flags |= 16 /* Boolean */;
37908             type.intrinsicName = "boolean";
37909             return type;
37910         }
37911         function createObjectType(objectFlags, symbol) {
37912             var type = createType(524288 /* Object */);
37913             type.objectFlags = objectFlags;
37914             type.symbol = symbol;
37915             type.members = undefined;
37916             type.properties = undefined;
37917             type.callSignatures = undefined;
37918             type.constructSignatures = undefined;
37919             type.stringIndexInfo = undefined;
37920             type.numberIndexInfo = undefined;
37921             return type;
37922         }
37923         function createTypeofType() {
37924             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
37925         }
37926         function createTypeParameter(symbol) {
37927             var type = createType(262144 /* TypeParameter */);
37928             if (symbol)
37929                 type.symbol = symbol;
37930             return type;
37931         }
37932         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
37933         // @, or #. A third underscore indicates an escaped form of an identifier that started
37934         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
37935         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
37936         function isReservedMemberName(name) {
37937             return name.charCodeAt(0) === 95 /* _ */ &&
37938                 name.charCodeAt(1) === 95 /* _ */ &&
37939                 name.charCodeAt(2) !== 95 /* _ */ &&
37940                 name.charCodeAt(2) !== 64 /* at */ &&
37941                 name.charCodeAt(2) !== 35 /* hash */;
37942         }
37943         function getNamedMembers(members) {
37944             var result;
37945             members.forEach(function (symbol, id) {
37946                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
37947                     (result || (result = [])).push(symbol);
37948                 }
37949             });
37950             return result || ts.emptyArray;
37951         }
37952         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37953             type.members = members;
37954             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
37955             type.callSignatures = callSignatures;
37956             type.constructSignatures = constructSignatures;
37957             type.stringIndexInfo = stringIndexInfo;
37958             type.numberIndexInfo = numberIndexInfo;
37959             return type;
37960         }
37961         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37962             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37963         }
37964         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
37965             var result;
37966             var _loop_7 = function (location) {
37967                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
37968                 if (location.locals && !isGlobalSourceFile(location)) {
37969                     if (result = callback(location.locals)) {
37970                         return { value: result };
37971                     }
37972                 }
37973                 switch (location.kind) {
37974                     case 290 /* SourceFile */:
37975                         if (!ts.isExternalOrCommonJsModule(location)) {
37976                             break;
37977                         }
37978                     // falls through
37979                     case 249 /* ModuleDeclaration */:
37980                         var sym = getSymbolOfNode(location);
37981                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
37982                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
37983                         // to one another anyway)
37984                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
37985                             return { value: result };
37986                         }
37987                         break;
37988                     case 245 /* ClassDeclaration */:
37989                     case 214 /* ClassExpression */:
37990                     case 246 /* InterfaceDeclaration */:
37991                         // Type parameters are bound into `members` lists so they can merge across declarations
37992                         // This is troublesome, since in all other respects, they behave like locals :cries:
37993                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
37994                         // lookup logic in terms of `resolveName` would be nice
37995                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
37996                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
37997                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
37998                         var table_1;
37999                         // TODO: Should this filtered table be cached in some way?
38000                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38001                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38002                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38003                             }
38004                         });
38005                         if (table_1 && (result = callback(table_1))) {
38006                             return { value: result };
38007                         }
38008                         break;
38009                 }
38010             };
38011             for (var location = enclosingDeclaration; location; location = location.parent) {
38012                 var state_2 = _loop_7(location);
38013                 if (typeof state_2 === "object")
38014                     return state_2.value;
38015             }
38016             return callback(globals);
38017         }
38018         function getQualifiedLeftMeaning(rightMeaning) {
38019             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38020             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38021         }
38022         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38023             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38024             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38025                 return undefined;
38026             }
38027             var id = "" + getSymbolId(symbol);
38028             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38029             if (!visitedSymbolTables) {
38030                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38031             }
38032             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38033             /**
38034              * @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)
38035              */
38036             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38037                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38038                     return undefined;
38039                 }
38040                 var result = trySymbolTable(symbols, ignoreQualification);
38041                 visitedSymbolTables.pop();
38042                 return result;
38043             }
38044             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38045                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38046                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38047                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38048                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38049             }
38050             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38051                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38052                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38053                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38054                     // check the symbol can be qualified, it is only then this symbol is accessible
38055                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38056                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38057             }
38058             function trySymbolTable(symbols, ignoreQualification) {
38059                 // If symbol is directly available by its name in the symbol table
38060                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38061                     return [symbol];
38062                 }
38063                 // Check if symbol is any of the aliases in scope
38064                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38065                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38066                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38067                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38068                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38069                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38070                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38071                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38072                         // See similar comment in `resolveName` for details
38073                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38074                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38075                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38076                         if (candidate) {
38077                             return candidate;
38078                         }
38079                     }
38080                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38081                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38082                             return [symbol];
38083                         }
38084                     }
38085                 });
38086                 // 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
38087                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38088             }
38089             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38090                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38091                     return [symbolFromSymbolTable];
38092                 }
38093                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38094                 // but only if the symbolFromSymbolTable can be qualified
38095                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38096                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38097                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38098                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38099                 }
38100             }
38101         }
38102         function needsQualification(symbol, enclosingDeclaration, meaning) {
38103             var qualify = false;
38104             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38105                 // If symbol of this name is not available in the symbol table we are ok
38106                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38107                 if (!symbolFromSymbolTable) {
38108                     // Continue to the next symbol table
38109                     return false;
38110                 }
38111                 // If the symbol with this name is present it should refer to the symbol
38112                 if (symbolFromSymbolTable === symbol) {
38113                     // No need to qualify
38114                     return true;
38115                 }
38116                 // Qualify if the symbol from symbol table has same meaning as expected
38117                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38118                 if (symbolFromSymbolTable.flags & meaning) {
38119                     qualify = true;
38120                     return true;
38121                 }
38122                 // Continue to the next symbol table
38123                 return false;
38124             });
38125             return qualify;
38126         }
38127         function isPropertyOrMethodDeclarationSymbol(symbol) {
38128             if (symbol.declarations && symbol.declarations.length) {
38129                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38130                     var declaration = _a[_i];
38131                     switch (declaration.kind) {
38132                         case 159 /* PropertyDeclaration */:
38133                         case 161 /* MethodDeclaration */:
38134                         case 163 /* GetAccessor */:
38135                         case 164 /* SetAccessor */:
38136                             continue;
38137                         default:
38138                             return false;
38139                     }
38140                 }
38141                 return true;
38142             }
38143             return false;
38144         }
38145         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38146             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38147             return access.accessibility === 0 /* Accessible */;
38148         }
38149         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38150             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38151             return access.accessibility === 0 /* Accessible */;
38152         }
38153         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38154             if (!ts.length(symbols))
38155                 return;
38156             var hadAccessibleChain;
38157             var earlyModuleBail = false;
38158             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38159                 var symbol = _a[_i];
38160                 // Symbol is accessible if it by itself is accessible
38161                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38162                 if (accessibleSymbolChain) {
38163                     hadAccessibleChain = symbol;
38164                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38165                     if (hasAccessibleDeclarations) {
38166                         return hasAccessibleDeclarations;
38167                     }
38168                 }
38169                 else {
38170                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38171                         if (shouldComputeAliasesToMakeVisible) {
38172                             earlyModuleBail = true;
38173                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38174                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38175                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38176                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38177                             continue;
38178                         }
38179                         // Any meaning of a module symbol is always accessible via an `import` type
38180                         return {
38181                             accessibility: 0 /* Accessible */
38182                         };
38183                     }
38184                 }
38185                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38186                 // It could be a qualified symbol and hence verify the path
38187                 // e.g.:
38188                 // module m {
38189                 //     export class c {
38190                 //     }
38191                 // }
38192                 // const x: typeof m.c
38193                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38194                 // we are going to see if c can be accessed in scope directly.
38195                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38196                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38197                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38198                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38199                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38200                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38201                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38202                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38203                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38204                         containers = [getSymbolOfNode(firstDecl.parent)];
38205                     }
38206                 }
38207                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38208                 if (parentResult) {
38209                     return parentResult;
38210                 }
38211             }
38212             if (earlyModuleBail) {
38213                 return {
38214                     accessibility: 0 /* Accessible */
38215                 };
38216             }
38217             if (hadAccessibleChain) {
38218                 return {
38219                     accessibility: 1 /* NotAccessible */,
38220                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38221                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38222                 };
38223             }
38224         }
38225         /**
38226          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38227          *
38228          * @param symbol a Symbol to check if accessible
38229          * @param enclosingDeclaration a Node containing reference to the symbol
38230          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38231          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38232          */
38233         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38234             if (symbol && enclosingDeclaration) {
38235                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38236                 if (result) {
38237                     return result;
38238                 }
38239                 // This could be a symbol that is not exported in the external module
38240                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38241                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38242                 if (symbolExternalModule) {
38243                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38244                     if (symbolExternalModule !== enclosingExternalModule) {
38245                         // name from different external module that is not visible
38246                         return {
38247                             accessibility: 2 /* CannotBeNamed */,
38248                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38249                             errorModuleName: symbolToString(symbolExternalModule)
38250                         };
38251                     }
38252                 }
38253                 // Just a local name that is not accessible
38254                 return {
38255                     accessibility: 1 /* NotAccessible */,
38256                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38257                 };
38258             }
38259             return { accessibility: 0 /* Accessible */ };
38260         }
38261         function getExternalModuleContainer(declaration) {
38262             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38263             return node && getSymbolOfNode(node);
38264         }
38265         function hasExternalModuleSymbol(declaration) {
38266             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38267         }
38268         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38269             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38270         }
38271         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38272             var aliasesToMakeVisible;
38273             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38274                 return undefined;
38275             }
38276             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38277             function getIsDeclarationVisible(declaration) {
38278                 if (!isDeclarationVisible(declaration)) {
38279                     // Mark the unexported alias as visible if its parent is visible
38280                     // because these kind of aliases can be used to name types in declaration file
38281                     var anyImportSyntax = getAnyImportSyntax(declaration);
38282                     if (anyImportSyntax &&
38283                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38284                         isDeclarationVisible(anyImportSyntax.parent)) {
38285                         return addVisibleAlias(declaration, anyImportSyntax);
38286                     }
38287                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38288                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38289                         isDeclarationVisible(declaration.parent.parent.parent)) {
38290                         return addVisibleAlias(declaration, declaration.parent.parent);
38291                     }
38292                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38293                         && !ts.hasModifier(declaration, 1 /* Export */)
38294                         && isDeclarationVisible(declaration.parent)) {
38295                         return addVisibleAlias(declaration, declaration);
38296                     }
38297                     // Declaration is not visible
38298                     return false;
38299                 }
38300                 return true;
38301             }
38302             function addVisibleAlias(declaration, aliasingStatement) {
38303                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38304                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38305                 // since we will do the emitting later in trackSymbol.
38306                 if (shouldComputeAliasToMakeVisible) {
38307                     getNodeLinks(declaration).isVisible = true;
38308                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38309                 }
38310                 return true;
38311             }
38312         }
38313         function isEntityNameVisible(entityName, enclosingDeclaration) {
38314             // get symbol of the first identifier of the entityName
38315             var meaning;
38316             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38317                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38318                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38319                 // Typeof value
38320                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38321             }
38322             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38323                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38324                 // Left identifier from type reference or TypeAlias
38325                 // Entity name of the import declaration
38326                 meaning = 1920 /* Namespace */;
38327             }
38328             else {
38329                 // Type Reference or TypeAlias entity = Identifier
38330                 meaning = 788968 /* Type */;
38331             }
38332             var firstIdentifier = ts.getFirstIdentifier(entityName);
38333             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38334             // Verify if the symbol is accessible
38335             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38336                 accessibility: 1 /* NotAccessible */,
38337                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38338                 errorNode: firstIdentifier
38339             };
38340         }
38341         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38342             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38343             var nodeFlags = 70221824 /* IgnoreErrors */;
38344             if (flags & 2 /* UseOnlyExternalAliasing */) {
38345                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38346             }
38347             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38348                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38349             }
38350             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38351                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38352             }
38353             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38354                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38355             }
38356             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38357             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38358             function symbolToStringWorker(writer) {
38359                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38360                 var printer = ts.createPrinter({ removeComments: true });
38361                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38362                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38363                 return writer;
38364             }
38365         }
38366         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38367             if (flags === void 0) { flags = 0 /* None */; }
38368             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38369             function signatureToStringWorker(writer) {
38370                 var sigOutput;
38371                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38372                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38373                 }
38374                 else {
38375                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38376                 }
38377                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38378                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38379                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38380                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38381                 return writer;
38382             }
38383         }
38384         function typeToString(type, enclosingDeclaration, flags, writer) {
38385             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38386             if (writer === void 0) { writer = ts.createTextWriter(""); }
38387             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38388             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38389             if (typeNode === undefined)
38390                 return ts.Debug.fail("should always get typenode");
38391             var options = { removeComments: true };
38392             var printer = ts.createPrinter(options);
38393             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38394             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38395             var result = writer.getText();
38396             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38397             if (maxLength && result && result.length >= maxLength) {
38398                 return result.substr(0, maxLength - "...".length) + "...";
38399             }
38400             return result;
38401         }
38402         function getTypeNamesForErrorDisplay(left, right) {
38403             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38404             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38405             if (leftStr === rightStr) {
38406                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38407                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38408             }
38409             return [leftStr, rightStr];
38410         }
38411         function symbolValueDeclarationIsContextSensitive(symbol) {
38412             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38413         }
38414         function toNodeBuilderFlags(flags) {
38415             if (flags === void 0) { flags = 0 /* None */; }
38416             return flags & 814775659 /* NodeBuilderFlagsMask */;
38417         }
38418         function createNodeBuilder() {
38419             return {
38420                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38421                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38422                 },
38423                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38424                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38425                 },
38426                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38427                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38428                 },
38429                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38430                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38431                 },
38432                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38433                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38434                 },
38435                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38436                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38437                 },
38438                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38439                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38440                 },
38441                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38442                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38443                 },
38444                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38445                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38446                 },
38447             };
38448             function withContext(enclosingDeclaration, flags, tracker, cb) {
38449                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38450                 var context = {
38451                     enclosingDeclaration: enclosingDeclaration,
38452                     flags: flags || 0 /* None */,
38453                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38454                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38455                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38456                             getSourceFiles: function () { return host.getSourceFiles(); },
38457                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38458                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38459                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38460                             redirectTargetsMap: host.redirectTargetsMap,
38461                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38462                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38463                             fileExists: function (fileName) { return host.fileExists(fileName); },
38464                         } : undefined },
38465                     encounteredError: false,
38466                     visitedTypes: undefined,
38467                     symbolDepth: undefined,
38468                     inferTypeParameters: undefined,
38469                     approximateLength: 0
38470                 };
38471                 var resultingNode = cb(context);
38472                 return context.encounteredError ? undefined : resultingNode;
38473             }
38474             function checkTruncationLength(context) {
38475                 if (context.truncating)
38476                     return context.truncating;
38477                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38478             }
38479             function typeToTypeNodeHelper(type, context) {
38480                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38481                     cancellationToken.throwIfCancellationRequested();
38482                 }
38483                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38484                 context.flags &= ~8388608 /* InTypeAlias */;
38485                 if (!type) {
38486                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38487                         context.encounteredError = true;
38488                         return undefined; // TODO: GH#18217
38489                     }
38490                     context.approximateLength += 3;
38491                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38492                 }
38493                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38494                     type = getReducedType(type);
38495                 }
38496                 if (type.flags & 1 /* Any */) {
38497                     context.approximateLength += 3;
38498                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38499                 }
38500                 if (type.flags & 2 /* Unknown */) {
38501                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38502                 }
38503                 if (type.flags & 4 /* String */) {
38504                     context.approximateLength += 6;
38505                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38506                 }
38507                 if (type.flags & 8 /* Number */) {
38508                     context.approximateLength += 6;
38509                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38510                 }
38511                 if (type.flags & 64 /* BigInt */) {
38512                     context.approximateLength += 6;
38513                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38514                 }
38515                 if (type.flags & 16 /* Boolean */) {
38516                     context.approximateLength += 7;
38517                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38518                 }
38519                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38520                     var parentSymbol = getParentOfSymbol(type.symbol);
38521                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38522                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38523                         ? parentName
38524                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38525                     return enumLiteralName;
38526                 }
38527                 if (type.flags & 1056 /* EnumLike */) {
38528                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38529                 }
38530                 if (type.flags & 128 /* StringLiteral */) {
38531                     context.approximateLength += (type.value.length + 2);
38532                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38533                 }
38534                 if (type.flags & 256 /* NumberLiteral */) {
38535                     var value = type.value;
38536                     context.approximateLength += ("" + value).length;
38537                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38538                 }
38539                 if (type.flags & 2048 /* BigIntLiteral */) {
38540                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38541                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38542                 }
38543                 if (type.flags & 512 /* BooleanLiteral */) {
38544                     context.approximateLength += type.intrinsicName.length;
38545                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38546                 }
38547                 if (type.flags & 8192 /* UniqueESSymbol */) {
38548                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38549                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38550                             context.approximateLength += 6;
38551                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38552                         }
38553                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38554                             context.tracker.reportInaccessibleUniqueSymbolError();
38555                         }
38556                     }
38557                     context.approximateLength += 13;
38558                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38559                 }
38560                 if (type.flags & 16384 /* Void */) {
38561                     context.approximateLength += 4;
38562                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38563                 }
38564                 if (type.flags & 32768 /* Undefined */) {
38565                     context.approximateLength += 9;
38566                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38567                 }
38568                 if (type.flags & 65536 /* Null */) {
38569                     context.approximateLength += 4;
38570                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38571                 }
38572                 if (type.flags & 131072 /* Never */) {
38573                     context.approximateLength += 5;
38574                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38575                 }
38576                 if (type.flags & 4096 /* ESSymbol */) {
38577                     context.approximateLength += 6;
38578                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38579                 }
38580                 if (type.flags & 67108864 /* NonPrimitive */) {
38581                     context.approximateLength += 6;
38582                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38583                 }
38584                 if (isThisTypeParameter(type)) {
38585                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38586                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38587                             context.encounteredError = true;
38588                         }
38589                         if (context.tracker.reportInaccessibleThisError) {
38590                             context.tracker.reportInaccessibleThisError();
38591                         }
38592                     }
38593                     context.approximateLength += 4;
38594                     return ts.createThis();
38595                 }
38596                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38597                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38598                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38599                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38600                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38601                 }
38602                 var objectFlags = ts.getObjectFlags(type);
38603                 if (objectFlags & 4 /* Reference */) {
38604                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38605                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38606                 }
38607                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38608                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38609                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38610                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38611                     }
38612                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38613                         type.flags & 262144 /* TypeParameter */ &&
38614                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38615                         var name = typeParameterToName(type, context);
38616                         context.approximateLength += ts.idText(name).length;
38617                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38618                     }
38619                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38620                     return type.symbol
38621                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38622                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38623                 }
38624                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38625                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38626                     if (ts.length(types) === 1) {
38627                         return typeToTypeNodeHelper(types[0], context);
38628                     }
38629                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38630                     if (typeNodes && typeNodes.length > 0) {
38631                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38632                         return unionOrIntersectionTypeNode;
38633                     }
38634                     else {
38635                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38636                             context.encounteredError = true;
38637                         }
38638                         return undefined; // TODO: GH#18217
38639                     }
38640                 }
38641                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38642                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38643                     // The type is an object literal type.
38644                     return createAnonymousTypeNode(type);
38645                 }
38646                 if (type.flags & 4194304 /* Index */) {
38647                     var indexedType = type.type;
38648                     context.approximateLength += 6;
38649                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38650                     return ts.createTypeOperatorNode(indexTypeNode);
38651                 }
38652                 if (type.flags & 8388608 /* IndexedAccess */) {
38653                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38654                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38655                     context.approximateLength += 2;
38656                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38657                 }
38658                 if (type.flags & 16777216 /* Conditional */) {
38659                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38660                     var saveInferTypeParameters = context.inferTypeParameters;
38661                     context.inferTypeParameters = type.root.inferTypeParameters;
38662                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38663                     context.inferTypeParameters = saveInferTypeParameters;
38664                     var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
38665                     var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
38666                     context.approximateLength += 15;
38667                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38668                 }
38669                 if (type.flags & 33554432 /* Substitution */) {
38670                     return typeToTypeNodeHelper(type.baseType, context);
38671                 }
38672                 return ts.Debug.fail("Should be unreachable.");
38673                 function createMappedTypeNodeFromType(type) {
38674                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38675                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38676                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38677                     var appropriateConstraintTypeNode;
38678                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38679                         // We have a { [P in keyof T]: X }
38680                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38681                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38682                     }
38683                     else {
38684                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38685                     }
38686                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38687                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38688                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38689                     context.approximateLength += 10;
38690                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38691                 }
38692                 function createAnonymousTypeNode(type) {
38693                     var typeId = "" + type.id;
38694                     var symbol = type.symbol;
38695                     if (symbol) {
38696                         if (isJSConstructor(symbol.valueDeclaration)) {
38697                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38698                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38699                             return symbolToTypeNode(symbol, context, isInstanceType);
38700                         }
38701                         // Always use 'typeof T' for type of class, enum, and module objects
38702                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38703                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38704                             shouldWriteTypeOfFunctionSymbol()) {
38705                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38706                         }
38707                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38708                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38709                             var typeAlias = getTypeAliasForTypeLiteral(type);
38710                             if (typeAlias) {
38711                                 // The specified symbol flags need to be reinterpreted as type flags
38712                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38713                             }
38714                             else {
38715                                 return createElidedInformationPlaceholder(context);
38716                             }
38717                         }
38718                         else {
38719                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38720                         }
38721                     }
38722                     else {
38723                         // Anonymous types without a symbol are never circular.
38724                         return createTypeNodeFromObjectType(type);
38725                     }
38726                     function shouldWriteTypeOfFunctionSymbol() {
38727                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38728                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38729                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38730                             (symbol.parent || // is exported function symbol
38731                                 ts.forEach(symbol.declarations, function (declaration) {
38732                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38733                                 }));
38734                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38735                             // typeof is allowed only for static/non local functions
38736                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38737                                 (!(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
38738                         }
38739                     }
38740                 }
38741                 function visitAndTransformType(type, transform) {
38742                     var typeId = "" + type.id;
38743                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38744                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38745                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38746                             undefined;
38747                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38748                     // of types allows us to catch circular references to instantiations of the same anonymous type
38749                     if (!context.visitedTypes) {
38750                         context.visitedTypes = ts.createMap();
38751                     }
38752                     if (id && !context.symbolDepth) {
38753                         context.symbolDepth = ts.createMap();
38754                     }
38755                     var depth;
38756                     if (id) {
38757                         depth = context.symbolDepth.get(id) || 0;
38758                         if (depth > 10) {
38759                             return createElidedInformationPlaceholder(context);
38760                         }
38761                         context.symbolDepth.set(id, depth + 1);
38762                     }
38763                     context.visitedTypes.set(typeId, true);
38764                     var result = transform(type);
38765                     context.visitedTypes.delete(typeId);
38766                     if (id) {
38767                         context.symbolDepth.set(id, depth);
38768                     }
38769                     return result;
38770                 }
38771                 function createTypeNodeFromObjectType(type) {
38772                     if (isGenericMappedType(type)) {
38773                         return createMappedTypeNodeFromType(type);
38774                     }
38775                     var resolved = resolveStructuredTypeMembers(type);
38776                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38777                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38778                             context.approximateLength += 2;
38779                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38780                         }
38781                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38782                             var signature = resolved.callSignatures[0];
38783                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38784                             return signatureNode;
38785                         }
38786                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38787                             var signature = resolved.constructSignatures[0];
38788                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38789                             return signatureNode;
38790                         }
38791                     }
38792                     var savedFlags = context.flags;
38793                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38794                     var members = createTypeNodesFromResolvedType(resolved);
38795                     context.flags = savedFlags;
38796                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38797                     context.approximateLength += 2;
38798                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38799                 }
38800                 function typeReferenceToTypeNode(type) {
38801                     var typeArguments = getTypeArguments(type);
38802                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38803                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38804                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38805                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38806                         }
38807                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38808                         var arrayType = ts.createArrayTypeNode(elementType);
38809                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38810                     }
38811                     else if (type.target.objectFlags & 8 /* Tuple */) {
38812                         if (typeArguments.length > 0) {
38813                             var arity = getTypeReferenceArity(type);
38814                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38815                             var hasRestElement = type.target.hasRestElement;
38816                             if (tupleConstituentNodes) {
38817                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38818                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38819                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38820                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38821                                 }
38822                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38823                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38824                             }
38825                         }
38826                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
38827                             var tupleTypeNode = ts.createTupleTypeNode([]);
38828                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38829                         }
38830                         context.encounteredError = true;
38831                         return undefined; // TODO: GH#18217
38832                     }
38833                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
38834                         type.symbol.valueDeclaration &&
38835                         ts.isClassLike(type.symbol.valueDeclaration) &&
38836                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38837                         return createAnonymousTypeNode(type);
38838                     }
38839                     else {
38840                         var outerTypeParameters = type.target.outerTypeParameters;
38841                         var i = 0;
38842                         var resultType = void 0;
38843                         if (outerTypeParameters) {
38844                             var length_2 = outerTypeParameters.length;
38845                             while (i < length_2) {
38846                                 // Find group of type arguments for type parameters with the same declaring container.
38847                                 var start = i;
38848                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
38849                                 do {
38850                                     i++;
38851                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
38852                                 // When type parameters are their own type arguments for the whole group (i.e. we have
38853                                 // the default outer type arguments), we don't show the group.
38854                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
38855                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
38856                                     var flags_2 = context.flags;
38857                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38858                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
38859                                     context.flags = flags_2;
38860                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
38861                                 }
38862                             }
38863                         }
38864                         var typeArgumentNodes = void 0;
38865                         if (typeArguments.length > 0) {
38866                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
38867                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
38868                         }
38869                         var flags = context.flags;
38870                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38871                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
38872                         context.flags = flags;
38873                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
38874                     }
38875                 }
38876                 function appendReferenceToType(root, ref) {
38877                     if (ts.isImportTypeNode(root)) {
38878                         // first shift type arguments
38879                         var innerParams = root.typeArguments;
38880                         if (root.qualifier) {
38881                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
38882                         }
38883                         root.typeArguments = ref.typeArguments;
38884                         // then move qualifiers
38885                         var ids = getAccessStack(ref);
38886                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
38887                             var id = ids_1[_i];
38888                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
38889                         }
38890                         return root;
38891                     }
38892                     else {
38893                         // first shift type arguments
38894                         var innerParams = root.typeArguments;
38895                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
38896                         root.typeArguments = ref.typeArguments;
38897                         // then move qualifiers
38898                         var ids = getAccessStack(ref);
38899                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
38900                             var id = ids_2[_a];
38901                             root.typeName = ts.createQualifiedName(root.typeName, id);
38902                         }
38903                         return root;
38904                     }
38905                 }
38906                 function getAccessStack(ref) {
38907                     var state = ref.typeName;
38908                     var ids = [];
38909                     while (!ts.isIdentifier(state)) {
38910                         ids.unshift(state.right);
38911                         state = state.left;
38912                     }
38913                     ids.unshift(state);
38914                     return ids;
38915                 }
38916                 function createTypeNodesFromResolvedType(resolvedType) {
38917                     if (checkTruncationLength(context)) {
38918                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
38919                     }
38920                     var typeElements = [];
38921                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
38922                         var signature = _a[_i];
38923                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
38924                     }
38925                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
38926                         var signature = _c[_b];
38927                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
38928                     }
38929                     if (resolvedType.stringIndexInfo) {
38930                         var indexSignature = void 0;
38931                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
38932                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
38933                             indexSignature.type = createElidedInformationPlaceholder(context);
38934                         }
38935                         else {
38936                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
38937                         }
38938                         typeElements.push(indexSignature);
38939                     }
38940                     if (resolvedType.numberIndexInfo) {
38941                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
38942                     }
38943                     var properties = resolvedType.properties;
38944                     if (!properties) {
38945                         return typeElements;
38946                     }
38947                     var i = 0;
38948                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
38949                         var propertySymbol = properties_1[_d];
38950                         i++;
38951                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
38952                             if (propertySymbol.flags & 4194304 /* Prototype */) {
38953                                 continue;
38954                             }
38955                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
38956                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
38957                             }
38958                         }
38959                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
38960                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
38961                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
38962                             break;
38963                         }
38964                         addPropertyToElementList(propertySymbol, context, typeElements);
38965                     }
38966                     return typeElements.length ? typeElements : undefined;
38967                 }
38968             }
38969             function createElidedInformationPlaceholder(context) {
38970                 context.approximateLength += 3;
38971                 if (!(context.flags & 1 /* NoTruncation */)) {
38972                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
38973                 }
38974                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38975             }
38976             function addPropertyToElementList(propertySymbol, context, typeElements) {
38977                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
38978                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
38979                     anyType : getTypeOfSymbol(propertySymbol);
38980                 var saveEnclosingDeclaration = context.enclosingDeclaration;
38981                 context.enclosingDeclaration = undefined;
38982                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
38983                     var decl = ts.first(propertySymbol.declarations);
38984                     if (hasLateBindableName(decl)) {
38985                         if (ts.isBinaryExpression(decl)) {
38986                             var name = ts.getNameOfDeclaration(decl);
38987                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
38988                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
38989                             }
38990                         }
38991                         else {
38992                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
38993                         }
38994                     }
38995                 }
38996                 context.enclosingDeclaration = saveEnclosingDeclaration;
38997                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
38998                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
38999                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39000                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39001                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39002                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39003                         var signature = signatures_1[_i];
39004                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39005                         methodDeclaration.name = propertyName;
39006                         methodDeclaration.questionToken = optionalToken;
39007                         typeElements.push(preserveCommentsOn(methodDeclaration));
39008                     }
39009                 }
39010                 else {
39011                     var savedFlags = context.flags;
39012                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39013                     var propertyTypeNode = void 0;
39014                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39015                         propertyTypeNode = createElidedInformationPlaceholder(context);
39016                     }
39017                     else {
39018                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39019                     }
39020                     context.flags = savedFlags;
39021                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39022                     if (modifiers) {
39023                         context.approximateLength += 9;
39024                     }
39025                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39026                     /*initializer*/ undefined);
39027                     typeElements.push(preserveCommentsOn(propertySignature));
39028                 }
39029                 function preserveCommentsOn(node) {
39030                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39031                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39032                         var commentText = d.comment;
39033                         if (commentText) {
39034                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39035                         }
39036                     }
39037                     else if (propertySymbol.valueDeclaration) {
39038                         // Copy comments to node for declaration emit
39039                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39040                     }
39041                     return node;
39042                 }
39043             }
39044             function mapToTypeNodes(types, context, isBareList) {
39045                 if (ts.some(types)) {
39046                     if (checkTruncationLength(context)) {
39047                         if (!isBareList) {
39048                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39049                         }
39050                         else if (types.length > 2) {
39051                             return [
39052                                 typeToTypeNodeHelper(types[0], context),
39053                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39054                                 typeToTypeNodeHelper(types[types.length - 1], context)
39055                             ];
39056                         }
39057                     }
39058                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39059                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39060                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39061                     var result_3 = [];
39062                     var i = 0;
39063                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39064                         var type = types_1[_i];
39065                         i++;
39066                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39067                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39068                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39069                             if (typeNode_1) {
39070                                 result_3.push(typeNode_1);
39071                             }
39072                             break;
39073                         }
39074                         context.approximateLength += 2; // Account for whitespace + separator
39075                         var typeNode = typeToTypeNodeHelper(type, context);
39076                         if (typeNode) {
39077                             result_3.push(typeNode);
39078                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39079                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39080                             }
39081                         }
39082                     }
39083                     if (seenNames) {
39084                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39085                         // occurrences of the same name actually come from different
39086                         // namespaces, go through the single-identifier type reference nodes
39087                         // we just generated, and see if any names were generated more than
39088                         // once while referring to different types. If so, regenerate the
39089                         // type node for each entry by that name with the
39090                         // `UseFullyQualifiedType` flag enabled.
39091                         var saveContextFlags = context.flags;
39092                         context.flags |= 64 /* UseFullyQualifiedType */;
39093                         seenNames.forEach(function (types) {
39094                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39095                                 var a = _a[0];
39096                                 var b = _b[0];
39097                                 return typesAreSameReference(a, b);
39098                             })) {
39099                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39100                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39101                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39102                                 }
39103                             }
39104                         });
39105                         context.flags = saveContextFlags;
39106                     }
39107                     return result_3;
39108                 }
39109             }
39110             function typesAreSameReference(a, b) {
39111                 return a === b
39112                     || !!a.symbol && a.symbol === b.symbol
39113                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39114             }
39115             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39116                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39117                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39118                 var indexingParameter = ts.createParameter(
39119                 /*decorators*/ undefined, 
39120                 /*modifiers*/ undefined, 
39121                 /*dotDotDotToken*/ undefined, name, 
39122                 /*questionToken*/ undefined, indexerTypeNode, 
39123                 /*initializer*/ undefined);
39124                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39125                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39126                     context.encounteredError = true;
39127                 }
39128                 context.approximateLength += (name.length + 4);
39129                 return ts.createIndexSignature(
39130                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39131             }
39132             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39133                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39134                 if (suppressAny)
39135                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39136                 var typeParameters;
39137                 var typeArguments;
39138                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39139                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39140                 }
39141                 else {
39142                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39143                 }
39144                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39145                 if (signature.thisParameter) {
39146                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39147                     parameters.unshift(thisParameter);
39148                 }
39149                 var returnTypeNode;
39150                 var typePredicate = getTypePredicateOfSignature(signature);
39151                 if (typePredicate) {
39152                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39153                         ts.createToken(124 /* AssertsKeyword */) :
39154                         undefined;
39155                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39156                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39157                         ts.createThisTypeNode();
39158                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39159                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39160                 }
39161                 else {
39162                     var returnType = getReturnTypeOfSignature(signature);
39163                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39164                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39165                     }
39166                     else if (!suppressAny) {
39167                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39168                     }
39169                 }
39170                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39171                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39172             }
39173             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39174                 var savedContextFlags = context.flags;
39175                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39176                 var name = typeParameterToName(type, context);
39177                 var defaultParameter = getDefaultFromTypeParameter(type);
39178                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39179                 context.flags = savedContextFlags;
39180                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39181             }
39182             function typeParameterToDeclaration(type, context, constraint) {
39183                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39184                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39185                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39186             }
39187             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39188                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39189                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39190                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39191                 }
39192                 var parameterType = getTypeOfSymbol(parameterSymbol);
39193                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39194                     parameterType = getOptionalType(parameterType);
39195                 }
39196                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39197                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39198                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39199                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39200                 var name = parameterDeclaration ? parameterDeclaration.name ?
39201                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39202                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39203                             cloneBindingName(parameterDeclaration.name) :
39204                     ts.symbolName(parameterSymbol) :
39205                     ts.symbolName(parameterSymbol);
39206                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39207                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39208                 var parameterNode = ts.createParameter(
39209                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39210                 /*initializer*/ undefined);
39211                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39212                 return parameterNode;
39213                 function cloneBindingName(node) {
39214                     return elideInitializerAndSetEmitFlags(node);
39215                     function elideInitializerAndSetEmitFlags(node) {
39216                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39217                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39218                         }
39219                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39220                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39221                         if (clone.kind === 191 /* BindingElement */) {
39222                             clone.initializer = undefined;
39223                         }
39224                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39225                     }
39226                 }
39227             }
39228             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39229                 if (!context.tracker.trackSymbol)
39230                     return;
39231                 // get symbol of the first identifier of the entityName
39232                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39233                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39234                 if (name) {
39235                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39236                 }
39237             }
39238             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39239                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39240                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39241             }
39242             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39243                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39244                 var chain;
39245                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39246                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39247                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39248                     ts.Debug.assert(chain && chain.length > 0);
39249                 }
39250                 else {
39251                     chain = [symbol];
39252                 }
39253                 return chain;
39254                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39255                 function getSymbolChain(symbol, meaning, endOfChain) {
39256                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39257                     var parentSpecifiers;
39258                     if (!accessibleSymbolChain ||
39259                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39260                         // Go up and add our parent.
39261                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39262                         if (ts.length(parents_1)) {
39263                             parentSpecifiers = parents_1.map(function (symbol) {
39264                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39265                                     ? getSpecifierForModuleSymbol(symbol, context)
39266                                     : undefined;
39267                             });
39268                             var indices = parents_1.map(function (_, i) { return i; });
39269                             indices.sort(sortByBestName);
39270                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39271                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39272                                 var parent = sortedParents_1[_i];
39273                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39274                                 if (parentChain) {
39275                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39276                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39277                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39278                                         // No need to lookup an alias for the symbol in itself
39279                                         accessibleSymbolChain = parentChain;
39280                                         break;
39281                                     }
39282                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39283                                     break;
39284                                 }
39285                             }
39286                         }
39287                     }
39288                     if (accessibleSymbolChain) {
39289                         return accessibleSymbolChain;
39290                     }
39291                     if (
39292                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39293                     endOfChain ||
39294                         // If a parent symbol is an anonymous type, don't write it.
39295                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39296                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39297                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39298                             return;
39299                         }
39300                         return [symbol];
39301                     }
39302                     function sortByBestName(a, b) {
39303                         var specifierA = parentSpecifiers[a];
39304                         var specifierB = parentSpecifiers[b];
39305                         if (specifierA && specifierB) {
39306                             var isBRelative = ts.pathIsRelative(specifierB);
39307                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39308                                 // Both relative or both non-relative, sort by number of parts
39309                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39310                             }
39311                             if (isBRelative) {
39312                                 // A is non-relative, B is relative: prefer A
39313                                 return -1;
39314                             }
39315                             // A is relative, B is non-relative: prefer B
39316                             return 1;
39317                         }
39318                         return 0;
39319                     }
39320                 }
39321             }
39322             function typeParametersToTypeParameterDeclarations(symbol, context) {
39323                 var typeParameterNodes;
39324                 var targetSymbol = getTargetSymbol(symbol);
39325                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39326                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39327                 }
39328                 return typeParameterNodes;
39329             }
39330             function lookupTypeParameterNodes(chain, index, context) {
39331                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39332                 var symbol = chain[index];
39333                 var symbolId = "" + getSymbolId(symbol);
39334                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39335                     return undefined;
39336                 }
39337                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39338                 var typeParameterNodes;
39339                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39340                     var parentSymbol = symbol;
39341                     var nextSymbol_1 = chain[index + 1];
39342                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39343                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39344                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39345                     }
39346                     else {
39347                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39348                     }
39349                 }
39350                 return typeParameterNodes;
39351             }
39352             /**
39353              * Given A[B][C][D], finds A[B]
39354              */
39355             function getTopmostIndexedAccessType(top) {
39356                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39357                     return getTopmostIndexedAccessType(top.objectType);
39358                 }
39359                 return top;
39360             }
39361             function getSpecifierForModuleSymbol(symbol, context) {
39362                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39363                 if (!file) {
39364                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39365                     if (equivalentFileSymbol) {
39366                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39367                     }
39368                 }
39369                 if (file && file.moduleName !== undefined) {
39370                     // Use the amd name if it is available
39371                     return file.moduleName;
39372                 }
39373                 if (!file) {
39374                     if (context.tracker.trackReferencedAmbientModule) {
39375                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39376                         if (ts.length(ambientDecls)) {
39377                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39378                                 var decl = ambientDecls_1[_i];
39379                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39380                             }
39381                         }
39382                     }
39383                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39384                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39385                     }
39386                 }
39387                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39388                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39389                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39390                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39391                     }
39392                     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
39393                 }
39394                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39395                 var links = getSymbolLinks(symbol);
39396                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39397                 if (!specifier) {
39398                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39399                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39400                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39401                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39402                     // specifier preference
39403                     var moduleResolverHost = context.tracker.moduleResolverHost;
39404                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39405                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39406                     links.specifierCache = links.specifierCache || ts.createMap();
39407                     links.specifierCache.set(contextFile.path, specifier);
39408                 }
39409                 return specifier;
39410             }
39411             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39412                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39413                 var isTypeOf = meaning === 111551 /* Value */;
39414                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39415                     // module is root, must use `ImportTypeNode`
39416                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39417                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39418                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39419                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39420                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39421                         // since declaration files with these kinds of references are liable to fail when published :(
39422                         context.encounteredError = true;
39423                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39424                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39425                         }
39426                     }
39427                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39428                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39429                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39430                     context.approximateLength += specifier.length + 10; // specifier + import("")
39431                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39432                         if (nonRootParts) {
39433                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39434                             lastId.typeArguments = undefined;
39435                         }
39436                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39437                     }
39438                     else {
39439                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39440                         var qualifier = splitNode.objectType.typeName;
39441                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39442                     }
39443                 }
39444                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39445                 if (ts.isIndexedAccessTypeNode(entityName)) {
39446                     return entityName; // Indexed accesses can never be `typeof`
39447                 }
39448                 if (isTypeOf) {
39449                     return ts.createTypeQueryNode(entityName);
39450                 }
39451                 else {
39452                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39453                     var lastTypeArgs = lastId.typeArguments;
39454                     lastId.typeArguments = undefined;
39455                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39456                 }
39457                 function createAccessFromSymbolChain(chain, index, stopper) {
39458                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39459                     var symbol = chain[index];
39460                     var parent = chain[index - 1];
39461                     var symbolName;
39462                     if (index === 0) {
39463                         context.flags |= 16777216 /* InInitialEntityName */;
39464                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39465                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39466                         context.flags ^= 16777216 /* InInitialEntityName */;
39467                     }
39468                     else {
39469                         if (parent && getExportsOfSymbol(parent)) {
39470                             var exports_1 = getExportsOfSymbol(parent);
39471                             ts.forEachEntry(exports_1, function (ex, name) {
39472                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39473                                     symbolName = ts.unescapeLeadingUnderscores(name);
39474                                     return true;
39475                                 }
39476                             });
39477                         }
39478                     }
39479                     if (!symbolName) {
39480                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39481                     }
39482                     context.approximateLength += symbolName.length + 1;
39483                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39484                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39485                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39486                         // Should use an indexed access
39487                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39488                         if (ts.isIndexedAccessTypeNode(LHS)) {
39489                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39490                         }
39491                         else {
39492                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39493                         }
39494                     }
39495                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39496                     identifier.symbol = symbol;
39497                     if (index > stopper) {
39498                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39499                         if (!ts.isEntityName(LHS)) {
39500                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39501                         }
39502                         return ts.createQualifiedName(LHS, identifier);
39503                     }
39504                     return identifier;
39505                 }
39506             }
39507             function typeParameterShadowsNameInScope(escapedName, context, type) {
39508                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39509                 if (result) {
39510                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39511                         return false;
39512                     }
39513                     return true;
39514                 }
39515                 return false;
39516             }
39517             function typeParameterToName(type, context) {
39518                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39519                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39520                     if (cached) {
39521                         return cached;
39522                     }
39523                 }
39524                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39525                 if (!(result.kind & 75 /* Identifier */)) {
39526                     return ts.createIdentifier("(Missing type parameter)");
39527                 }
39528                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39529                     var rawtext = result.escapedText;
39530                     var i = 0;
39531                     var text = rawtext;
39532                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39533                         i++;
39534                         text = rawtext + "_" + i;
39535                     }
39536                     if (text !== rawtext) {
39537                         result = ts.createIdentifier(text, result.typeArguments);
39538                     }
39539                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39540                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39541                 }
39542                 return result;
39543             }
39544             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39545                 var chain = lookupSymbolChain(symbol, context, meaning);
39546                 if (expectsIdentifier && chain.length !== 1
39547                     && !context.encounteredError
39548                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39549                     context.encounteredError = true;
39550                 }
39551                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39552                 function createEntityNameFromSymbolChain(chain, index) {
39553                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39554                     var symbol = chain[index];
39555                     if (index === 0) {
39556                         context.flags |= 16777216 /* InInitialEntityName */;
39557                     }
39558                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39559                     if (index === 0) {
39560                         context.flags ^= 16777216 /* InInitialEntityName */;
39561                     }
39562                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39563                     identifier.symbol = symbol;
39564                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39565                 }
39566             }
39567             function symbolToExpression(symbol, context, meaning) {
39568                 var chain = lookupSymbolChain(symbol, context, meaning);
39569                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39570                 function createExpressionFromSymbolChain(chain, index) {
39571                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39572                     var symbol = chain[index];
39573                     if (index === 0) {
39574                         context.flags |= 16777216 /* InInitialEntityName */;
39575                     }
39576                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39577                     if (index === 0) {
39578                         context.flags ^= 16777216 /* InInitialEntityName */;
39579                     }
39580                     var firstChar = symbolName.charCodeAt(0);
39581                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39582                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39583                     }
39584                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39585                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39586                         ts.isIdentifierStart(firstChar, languageVersion);
39587                     if (index === 0 || canUsePropertyAccess) {
39588                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39589                         identifier.symbol = symbol;
39590                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39591                     }
39592                     else {
39593                         if (firstChar === 91 /* openBracket */) {
39594                             symbolName = symbolName.substring(1, symbolName.length - 1);
39595                             firstChar = symbolName.charCodeAt(0);
39596                         }
39597                         var expression = void 0;
39598                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39599                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39600                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39601                         }
39602                         else if (("" + +symbolName) === symbolName) {
39603                             expression = ts.createLiteral(+symbolName);
39604                         }
39605                         if (!expression) {
39606                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39607                             expression.symbol = symbol;
39608                         }
39609                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39610                     }
39611                 }
39612             }
39613             function isSingleQuotedStringNamed(d) {
39614                 var name = ts.getNameOfDeclaration(d);
39615                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39616                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39617                     return true;
39618                 }
39619                 return false;
39620             }
39621             function getPropertyNameNodeForSymbol(symbol, context) {
39622                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39623                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39624                 if (fromNameType) {
39625                     return fromNameType;
39626                 }
39627                 if (ts.isKnownSymbol(symbol)) {
39628                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39629                 }
39630                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39631                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39632             }
39633             // See getNameForSymbolFromNameType for a stringy equivalent
39634             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39635                 var nameType = getSymbolLinks(symbol).nameType;
39636                 if (nameType) {
39637                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39638                         var name = "" + nameType.value;
39639                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39640                             return ts.createLiteral(name, !!singleQuote);
39641                         }
39642                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39643                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39644                         }
39645                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39646                     }
39647                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39648                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39649                     }
39650                 }
39651             }
39652             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39653                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39654             }
39655             function cloneNodeBuilderContext(context) {
39656                 var initial = __assign({}, context);
39657                 // Make type parameters created within this context not consume the name outside this context
39658                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39659                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39660                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39661                 // were multiple generic overloads with similar generated type parameter names
39662                 // The effect:
39663                 // When we write out
39664                 // export const x: <T>(x: T) => T
39665                 // export const y: <T>(x: T) => T
39666                 // we write it out like that, rather than as
39667                 // export const x: <T>(x: T) => T
39668                 // export const y: <T_1>(x: T_1) => T_1
39669                 if (initial.typeParameterNames) {
39670                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39671                 }
39672                 if (initial.typeParameterNamesByText) {
39673                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39674                 }
39675                 if (initial.typeParameterSymbolList) {
39676                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39677                 }
39678                 return initial;
39679             }
39680             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39681                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39682             }
39683             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39684                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39685             }
39686             /**
39687              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39688              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39689              */
39690             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39691                 if (type !== errorType && enclosingDeclaration) {
39692                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39693                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39694                         // try to reuse the existing annotation
39695                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39696                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39697                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39698                             if (result_4) {
39699                                 return result_4;
39700                             }
39701                         }
39702                     }
39703                 }
39704                 var oldFlags = context.flags;
39705                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39706                     type.symbol === symbol) {
39707                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39708                 }
39709                 var result = typeToTypeNodeHelper(type, context);
39710                 context.flags = oldFlags;
39711                 return result;
39712             }
39713             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39714                 if (type !== errorType && context.enclosingDeclaration) {
39715                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39716                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39717                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39718                         if (result) {
39719                             return result;
39720                         }
39721                     }
39722                 }
39723                 return typeToTypeNodeHelper(type, context);
39724             }
39725             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39726                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39727                     cancellationToken.throwIfCancellationRequested();
39728                 }
39729                 var hadError = false;
39730                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39731                 if (hadError) {
39732                     return undefined;
39733                 }
39734                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39735                 function visitExistingNodeTreeSymbols(node) {
39736                     var _a, _b;
39737                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39738                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39739                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39740                     }
39741                     if (ts.isJSDocUnknownType(node)) {
39742                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39743                     }
39744                     if (ts.isJSDocNullableType(node)) {
39745                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39746                     }
39747                     if (ts.isJSDocOptionalType(node)) {
39748                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39749                     }
39750                     if (ts.isJSDocNonNullableType(node)) {
39751                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39752                     }
39753                     if (ts.isJSDocVariadicType(node)) {
39754                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39755                     }
39756                     if (ts.isJSDocTypeLiteral(node)) {
39757                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39758                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39759                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39760                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39761                             return ts.createPropertySignature(
39762                             /*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 */), 
39763                             /*initializer*/ undefined);
39764                         }));
39765                     }
39766                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39767                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39768                     }
39769                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39770                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39771                             /*decorators*/ undefined, 
39772                             /*modifiers*/ undefined, [ts.createParameter(
39773                                 /*decorators*/ undefined, 
39774                                 /*modifiers*/ undefined, 
39775                                 /*dotdotdotToken*/ undefined, "x", 
39776                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39777                     }
39778                     if (ts.isJSDocFunctionType(node)) {
39779                         if (ts.isJSDocConstructSignature(node)) {
39780                             var newTypeNode_1;
39781                             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(
39782                             /*decorators*/ undefined, 
39783                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39784                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39785                         }
39786                         else {
39787                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39788                             /*decorators*/ undefined, 
39789                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39790                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39791                         }
39792                     }
39793                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39794                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39795                     }
39796                     if (ts.isLiteralImportTypeNode(node)) {
39797                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39798                     }
39799                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39800                         var leftmost = ts.getFirstIdentifier(node);
39801                         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)))) {
39802                             hadError = true;
39803                             return node;
39804                         }
39805                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39806                         if (sym) {
39807                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39808                                 hadError = true;
39809                             }
39810                             else {
39811                                 (_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 */);
39812                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39813                             }
39814                             if (ts.isIdentifier(node)) {
39815                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39816                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39817                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39818                             }
39819                         }
39820                     }
39821                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39822                     function getEffectiveDotDotDotForParameter(p) {
39823                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
39824                     }
39825                     function rewriteModuleSpecifier(parent, lit) {
39826                         if (bundled) {
39827                             if (context.tracker && context.tracker.moduleResolverHost) {
39828                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
39829                                 if (targetFile) {
39830                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
39831                                     var resolverHost = {
39832                                         getCanonicalFileName: getCanonicalFileName,
39833                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
39834                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
39835                                     };
39836                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
39837                                     return ts.createLiteral(newName);
39838                                 }
39839                             }
39840                         }
39841                         else {
39842                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
39843                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
39844                                 if (moduleSym) {
39845                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
39846                                 }
39847                             }
39848                         }
39849                         return lit;
39850                     }
39851                 }
39852             }
39853             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
39854                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
39855                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
39856                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
39857                 // declaration mapping
39858                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
39859                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
39860                 // we're trying to emit from later on)
39861                 var enclosingDeclaration = context.enclosingDeclaration;
39862                 var results = [];
39863                 var visitedSymbols = ts.createMap();
39864                 var deferredPrivates;
39865                 var oldcontext = context;
39866                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
39867                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
39868                             if (accessibleResult.accessibility === 0 /* Accessible */) {
39869                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
39870                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
39871                                 if (!(sym.flags & 4 /* Property */)) {
39872                                     includePrivateSymbol(chain[0]);
39873                                 }
39874                             }
39875                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
39876                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
39877                             }
39878                         } }) });
39879                 if (oldcontext.usedSymbolNames) {
39880                     oldcontext.usedSymbolNames.forEach(function (_, name) {
39881                         context.usedSymbolNames.set(name, true);
39882                     });
39883                 }
39884                 ts.forEachEntry(symbolTable, function (symbol, name) {
39885                     var baseName = ts.unescapeLeadingUnderscores(name);
39886                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
39887                 });
39888                 var addingDeclare = !bundled;
39889                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
39890                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
39891                     symbolTable = ts.createSymbolTable();
39892                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
39893                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
39894                 }
39895                 visitSymbolTable(symbolTable);
39896                 return mergeRedundantStatements(results);
39897                 function isIdentifierAndNotUndefined(node) {
39898                     return !!node && node.kind === 75 /* Identifier */;
39899                 }
39900                 function getNamesOfDeclaration(statement) {
39901                     if (ts.isVariableStatement(statement)) {
39902                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
39903                     }
39904                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
39905                 }
39906                 function flattenExportAssignedNamespace(statements) {
39907                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
39908                     var ns = ts.find(statements, ts.isModuleDeclaration);
39909                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
39910                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
39911                         ns.body && ts.isModuleBlock(ns.body)) {
39912                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
39913                         //  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
39914                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
39915                         if (ts.length(excessExports)) {
39916                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
39917                                 /*decorators*/ undefined, 
39918                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
39919                                 /*moduleSpecifier*/ undefined)]));
39920                         }
39921                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
39922                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
39923                             results = [];
39924                             ts.forEach(ns.body.statements, function (s) {
39925                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
39926                             });
39927                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
39928                         }
39929                     }
39930                     return statements;
39931                 }
39932                 function mergeExportDeclarations(statements) {
39933                     // Pass 2: Combine all `export {}` declarations
39934                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39935                     if (ts.length(exports) > 1) {
39936                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
39937                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
39938                             /*decorators*/ undefined, 
39939                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
39940                             /*moduleSpecifier*/ undefined)]);
39941                     }
39942                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
39943                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39944                     if (ts.length(reexports) > 1) {
39945                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
39946                         if (groups.length !== reexports.length) {
39947                             var _loop_8 = function (group_1) {
39948                                 if (group_1.length > 1) {
39949                                     // remove group members from statements and then merge group members and add back to statements
39950                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
39951                                         ts.createExportDeclaration(
39952                                         /*decorators*/ undefined, 
39953                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
39954                                     ]);
39955                                 }
39956                             };
39957                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
39958                                 var group_1 = groups_1[_i];
39959                                 _loop_8(group_1);
39960                             }
39961                         }
39962                     }
39963                     return statements;
39964                 }
39965                 function inlineExportModifiers(statements) {
39966                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
39967                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
39968                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
39969                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
39970                             if (!e.propertyName) {
39971                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
39972                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
39973                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
39974                                     ts.forEach(associated, addExportModifier);
39975                                     return undefined;
39976                                 }
39977                             }
39978                             return e;
39979                         });
39980                         if (!ts.length(replacements)) {
39981                             // all clauses removed, filter the export declaration
39982                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
39983                         }
39984                         else {
39985                             // some items filtered, others not - update the export declaration
39986                             // (mutating because why not, we're building a whole new tree here anyway)
39987                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
39988                         }
39989                     }
39990                     return statements;
39991                 }
39992                 function mergeRedundantStatements(statements) {
39993                     statements = flattenExportAssignedNamespace(statements);
39994                     statements = mergeExportDeclarations(statements);
39995                     statements = inlineExportModifiers(statements);
39996                     // 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
39997                     // declaration privacy is respected.
39998                     if (enclosingDeclaration &&
39999                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40000                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40001                         statements.push(ts.createEmptyExports());
40002                     }
40003                     return statements;
40004                 }
40005                 function canHaveExportModifier(node) {
40006                     return ts.isEnumDeclaration(node) ||
40007                         ts.isVariableStatement(node) ||
40008                         ts.isFunctionDeclaration(node) ||
40009                         ts.isClassDeclaration(node) ||
40010                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40011                         ts.isInterfaceDeclaration(node) ||
40012                         isTypeDeclaration(node);
40013                 }
40014                 function addExportModifier(statement) {
40015                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40016                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40017                     statement.modifierFlagsCache = 0;
40018                 }
40019                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40020                     var oldDeferredPrivates = deferredPrivates;
40021                     if (!suppressNewPrivateContext) {
40022                         deferredPrivates = ts.createMap();
40023                     }
40024                     symbolTable.forEach(function (symbol) {
40025                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40026                     });
40027                     if (!suppressNewPrivateContext) {
40028                         // deferredPrivates will be filled up by visiting the symbol table
40029                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40030                         // (As that's how a map iterator is defined to work)
40031                         deferredPrivates.forEach(function (symbol) {
40032                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40033                         });
40034                     }
40035                     deferredPrivates = oldDeferredPrivates;
40036                 }
40037                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40038                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40039                     // still skip reserializing it if we encounter the merged product later on
40040                     var visitedSym = getMergedSymbol(symbol);
40041                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40042                         return; // Already printed
40043                     }
40044                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40045                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40046                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40047                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40048                         var oldContext = context;
40049                         context = cloneNodeBuilderContext(context);
40050                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40051                         context = oldContext;
40052                         return result;
40053                     }
40054                 }
40055                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40056                 // or a merge of some number of those.
40057                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40058                 // each symbol in only one of the representations
40059                 // Also, synthesizing a default export of some kind
40060                 // If it's an alias: emit `export default ref`
40061                 // If it's a property: emit `export default _default` with a `_default` prop
40062                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40063                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40064                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40065                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40066                     var isDefault = symbol.escapedName === "default" /* Default */;
40067                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40068                         // 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` :(
40069                         context.encounteredError = true;
40070                         // TODO: Issue error via symbol tracker?
40071                         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
40072                     }
40073                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40074                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40075                     if (needsPostExportDefault) {
40076                         isPrivate = true;
40077                     }
40078                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40079                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40080                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40081                         symbol.escapedName !== "export=" /* ExportEquals */;
40082                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40083                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40084                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40085                     }
40086                     if (symbol.flags & 524288 /* TypeAlias */) {
40087                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40088                     }
40089                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40090                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40091                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40092                         && symbol.escapedName !== "export=" /* ExportEquals */
40093                         && !(symbol.flags & 4194304 /* Prototype */)
40094                         && !(symbol.flags & 32 /* Class */)
40095                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40096                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40097                     }
40098                     if (symbol.flags & 384 /* Enum */) {
40099                         serializeEnum(symbol, symbolName, modifierFlags);
40100                     }
40101                     if (symbol.flags & 32 /* Class */) {
40102                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40103                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40104                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40105                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40106                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40107                         }
40108                         else {
40109                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40110                         }
40111                     }
40112                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40113                         serializeModule(symbol, symbolName, modifierFlags);
40114                     }
40115                     if (symbol.flags & 64 /* Interface */) {
40116                         serializeInterface(symbol, symbolName, modifierFlags);
40117                     }
40118                     if (symbol.flags & 2097152 /* Alias */) {
40119                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40120                     }
40121                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40122                         serializeMaybeAliasAssignment(symbol);
40123                     }
40124                     if (symbol.flags & 8388608 /* ExportStar */) {
40125                         // synthesize export * from "moduleReference"
40126                         // Straightforward - only one thing to do - make an export declaration
40127                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40128                             var node = _a[_i];
40129                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40130                             if (!resolvedModule)
40131                                 continue;
40132                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40133                         }
40134                     }
40135                     if (needsPostExportDefault) {
40136                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40137                     }
40138                 }
40139                 function includePrivateSymbol(symbol) {
40140                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40141                         return;
40142                     ts.Debug.assertIsDefined(deferredPrivates);
40143                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40144                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40145                 }
40146                 function isExportingScope(enclosingDeclaration) {
40147                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40148                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40149                 }
40150                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40151                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40152                 function addResult(node, additionalModifierFlags) {
40153                     var newModifierFlags = 0 /* None */;
40154                     if (additionalModifierFlags & 1 /* Export */ &&
40155                         enclosingDeclaration &&
40156                         isExportingScope(enclosingDeclaration) &&
40157                         canHaveExportModifier(node)) {
40158                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40159                         newModifierFlags |= 1 /* Export */;
40160                     }
40161                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40162                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40163                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40164                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40165                         newModifierFlags |= 2 /* Ambient */;
40166                     }
40167                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40168                         newModifierFlags |= 512 /* Default */;
40169                     }
40170                     if (newModifierFlags) {
40171                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40172                         node.modifierFlagsCache = 0; // Reset computed flags cache
40173                     }
40174                     results.push(node);
40175                 }
40176                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40177                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40178                     var typeParams = getSymbolLinks(symbol).typeParameters;
40179                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40180                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40181                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40182                     var oldFlags = context.flags;
40183                     context.flags |= 8388608 /* InTypeAlias */;
40184                     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);
40185                     context.flags = oldFlags;
40186                 }
40187                 function serializeInterface(symbol, symbolName, modifierFlags) {
40188                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40189                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40190                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40191                     var baseTypes = getBaseTypes(interfaceType);
40192                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40193                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40194                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40195                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40196                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40197                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40198                     addResult(ts.createInterfaceDeclaration(
40199                     /*decorators*/ undefined, 
40200                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40201                 }
40202                 function getNamespaceMembersForSerialization(symbol) {
40203                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40204                 }
40205                 function isTypeOnlyNamespace(symbol) {
40206                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40207                 }
40208                 function serializeModule(symbol, symbolName, modifierFlags) {
40209                     var members = getNamespaceMembersForSerialization(symbol);
40210                     // 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)
40211                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40212                     var realMembers = locationMap.get("real") || ts.emptyArray;
40213                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40214                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40215                     // 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,
40216                     // so we don't even have placeholders to fill in.
40217                     if (ts.length(realMembers)) {
40218                         var localName = getInternalSymbolName(symbol, symbolName);
40219                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40220                     }
40221                     if (ts.length(mergedMembers)) {
40222                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40223                         var localName = getInternalSymbolName(symbol, symbolName);
40224                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40225                             /*decorators*/ undefined, 
40226                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40227                                 var _a, _b;
40228                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40229                                 var localName = getInternalSymbolName(s, name);
40230                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40231                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40232                                     (_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);
40233                                     return undefined;
40234                                 }
40235                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40236                                 includePrivateSymbol(target || s);
40237                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40238                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40239                             })))]);
40240                         addResult(ts.createModuleDeclaration(
40241                         /*decorators*/ undefined, 
40242                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40243                     }
40244                 }
40245                 function serializeEnum(symbol, symbolName, modifierFlags) {
40246                     addResult(ts.createEnumDeclaration(
40247                     /*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) {
40248                         // TODO: Handle computed names
40249                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40250                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40251                         // _on the declaration_, not on the declaration's symbol...
40252                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40253                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40254                     })), modifierFlags);
40255                 }
40256                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40257                     if (propertyAsAlias) {
40258                         serializeMaybeAliasAssignment(symbol);
40259                     }
40260                     else {
40261                         var type = getTypeOfSymbol(symbol);
40262                         var localName = getInternalSymbolName(symbol, symbolName);
40263                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40264                             // 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
40265                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40266                         }
40267                         else {
40268                             // 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!_
40269                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40270                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40271                                 : isConstVariable(symbol) ? 2 /* Const */
40272                                     : 1 /* Let */;
40273                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40274                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40275                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40276                                 textRange = textRange.parent.parent;
40277                             }
40278                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40279                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40280                             ], flags)), textRange);
40281                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40282                             if (name !== localName && !isPrivate) {
40283                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40284                                 // conflicts with a local declaration. For example, given input:
40285                                 // ```
40286                                 // function g() {}
40287                                 // module.exports.g = g
40288                                 // ```
40289                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40290                                 // Naively, we would emit
40291                                 // ```
40292                                 // function g() {}
40293                                 // export const g: typeof g;
40294                                 // ```
40295                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40296                                 // the export declaration shadows it.
40297                                 // To work around that, we instead write
40298                                 // ```
40299                                 // function g() {}
40300                                 // const g_1: typeof g;
40301                                 // export { g_1 as g };
40302                                 // ```
40303                                 // To create an export named `g` that does _not_ shadow the local `g`
40304                                 addResult(ts.createExportDeclaration(
40305                                 /*decorators*/ undefined, 
40306                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40307                             }
40308                         }
40309                     }
40310                 }
40311                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40312                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40313                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40314                         var sig = signatures_2[_i];
40315                         // Each overload becomes a separate function declaration, in order
40316                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40317                         decl.name = ts.createIdentifier(localName);
40318                         // for expressions assigned to `var`s, use the `var` as the text range
40319                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40320                     }
40321                     // Module symbol emit will take care of module-y members, provided it has exports
40322                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40323                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40324                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40325                     }
40326                 }
40327                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40328                     if (ts.length(props)) {
40329                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40330                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40331                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40332                             }) ? "local" : "remote";
40333                         });
40334                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40335                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40336                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40337                         // Example:
40338                         // import Foo_1 = require("./exporter");
40339                         // export namespace ns {
40340                         //     import Foo = Foo_1.Foo;
40341                         //     export { Foo };
40342                         //     export const c: number;
40343                         // }
40344                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40345                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40346                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40347                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40348                         // emit akin to the above would be needed.
40349                         // Add a namespace
40350                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40351                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40352                         fakespace.parent = enclosingDeclaration;
40353                         fakespace.locals = ts.createSymbolTable(props);
40354                         fakespace.symbol = props[0].parent;
40355                         var oldResults = results;
40356                         results = [];
40357                         var oldAddingDeclare = addingDeclare;
40358                         addingDeclare = false;
40359                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40360                         var oldContext = context;
40361                         context = subcontext;
40362                         // 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
40363                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40364                         context = oldContext;
40365                         addingDeclare = oldAddingDeclare;
40366                         var declarations = results;
40367                         results = oldResults;
40368                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40369                         fakespace.parent = undefined;
40370                         fakespace.locals = undefined;
40371                         fakespace.symbol = undefined;
40372                         fakespace.body = ts.createModuleBlock(declarations);
40373                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40374                     }
40375                 }
40376                 function isNamespaceMember(p) {
40377                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40378                 }
40379                 function serializeAsClass(symbol, localName, modifierFlags) {
40380                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40381                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40382                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40383                     var baseTypes = getBaseTypes(classType);
40384                     var implementsTypes = getImplementsTypes(classType);
40385                     var staticType = getTypeOfSymbol(symbol);
40386                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40387                     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); }))]);
40388                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40389                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40390                         // `valueDeclaration` could be undefined if inherited from
40391                         // a union/intersection base type, but inherited properties
40392                         // don't matter here.
40393                         var valueDecl = s.valueDeclaration;
40394                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40395                     });
40396                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40397                         // `valueDeclaration` could be undefined if inherited from
40398                         // a union/intersection base type, but inherited properties
40399                         // don't matter here.
40400                         var valueDecl = s.valueDeclaration;
40401                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40402                     });
40403                     // Boil down all private properties into a single one.
40404                     var privateProperties = hasPrivateIdentifier ?
40405                         [ts.createProperty(
40406                             /*decorators*/ undefined, 
40407                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40408                             /*questionOrExclamationToken*/ undefined, 
40409                             /*type*/ undefined, 
40410                             /*initializer*/ undefined)] :
40411                         ts.emptyArray;
40412                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40413                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40414                     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); });
40415                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40416                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40417                         var c = constructors_1[_i];
40418                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40419                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40420                         c.type = undefined;
40421                         c.typeParameters = undefined;
40422                     }
40423                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40424                     addResult(ts.setTextRange(ts.createClassDeclaration(
40425                     /*decorators*/ undefined, 
40426                     /*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);
40427                 }
40428                 function serializeAsAlias(symbol, localName, modifierFlags) {
40429                     // synthesize an alias, eg `export { symbolName as Name }`
40430                     // need to mark the alias `symbol` points at
40431                     // as something we need to serialize as a private declaration as well
40432                     var node = getDeclarationOfAliasSymbol(symbol);
40433                     if (!node)
40434                         return ts.Debug.fail();
40435                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40436                     if (!target) {
40437                         return;
40438                     }
40439                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40440                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40441                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40442                         verbatimTargetName = "default" /* Default */;
40443                     }
40444                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40445                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40446                     switch (node.kind) {
40447                         case 253 /* ImportEqualsDeclaration */:
40448                             // Could be a local `import localName = ns.member` or
40449                             // an external `import localName = require("whatever")`
40450                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40451                             addResult(ts.createImportEqualsDeclaration(
40452                             /*decorators*/ undefined, 
40453                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40454                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40455                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40456                             break;
40457                         case 252 /* NamespaceExportDeclaration */:
40458                             // export as namespace foo
40459                             // TODO: Not part of a file's local or export symbol tables
40460                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40461                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40462                             break;
40463                         case 255 /* ImportClause */:
40464                             addResult(ts.createImportDeclaration(
40465                             /*decorators*/ undefined, 
40466                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40467                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40468                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40469                             // In such cases, the `target` refers to the module itself already
40470                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40471                             break;
40472                         case 256 /* NamespaceImport */:
40473                             addResult(ts.createImportDeclaration(
40474                             /*decorators*/ undefined, 
40475                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40476                             break;
40477                         case 262 /* NamespaceExport */:
40478                             addResult(ts.createExportDeclaration(
40479                             /*decorators*/ undefined, 
40480                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40481                             break;
40482                         case 258 /* ImportSpecifier */:
40483                             addResult(ts.createImportDeclaration(
40484                             /*decorators*/ undefined, 
40485                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40486                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40487                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40488                             break;
40489                         case 263 /* ExportSpecifier */:
40490                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40491                             // which we must exactly preserve
40492                             var specifier = node.parent.parent.moduleSpecifier;
40493                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40494                             // another file
40495                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40496                             break;
40497                         case 259 /* ExportAssignment */:
40498                             serializeMaybeAliasAssignment(symbol);
40499                             break;
40500                         case 209 /* BinaryExpression */:
40501                         case 194 /* PropertyAccessExpression */:
40502                             // Could be best encoded as though an export specifier or as though an export assignment
40503                             // If name is default or export=, do an export assignment
40504                             // Otherwise do an export specifier
40505                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40506                                 serializeMaybeAliasAssignment(symbol);
40507                             }
40508                             else {
40509                                 serializeExportSpecifier(localName, targetName);
40510                             }
40511                             break;
40512                         default:
40513                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40514                     }
40515                 }
40516                 function serializeExportSpecifier(localName, targetName, specifier) {
40517                     addResult(ts.createExportDeclaration(
40518                     /*decorators*/ undefined, 
40519                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40520                 }
40521                 function serializeMaybeAliasAssignment(symbol) {
40522                     if (symbol.flags & 4194304 /* Prototype */) {
40523                         return;
40524                     }
40525                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40526                     var isExportEquals = name === "export=" /* ExportEquals */;
40527                     var isDefault = name === "default" /* Default */;
40528                     var isExportAssignment = isExportEquals || isDefault;
40529                     // synthesize export = ref
40530                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40531                     // a reference to another namespace/module which we may need to emit an `import` statement for
40532                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40533                     // serialize what the alias points to, preserve the declaration's initializer
40534                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40535                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40536                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40537                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40538                         // eg, `namespace A { export class B {} }; exports = A.B;`
40539                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40540                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40541                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40542                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40543                         if (referenced || target) {
40544                             includePrivateSymbol(referenced || target);
40545                         }
40546                         // We disable the context's symbol tracker for the duration of this name serialization
40547                         // as, by virtue of being here, the name is required to print something, and we don't want to
40548                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40549                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40550                         // into the containing scope anyway, so we want to skip the visibility checks.
40551                         var oldTrack = context.tracker.trackSymbol;
40552                         context.tracker.trackSymbol = ts.noop;
40553                         if (isExportAssignment) {
40554                             results.push(ts.createExportAssignment(
40555                             /*decorators*/ undefined, 
40556                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40557                         }
40558                         else {
40559                             if (first_1 === expr) {
40560                                 // serialize as `export {target as name}`
40561                                 serializeExportSpecifier(name, ts.idText(first_1));
40562                             }
40563                             else if (ts.isClassExpression(expr)) {
40564                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40565                             }
40566                             else {
40567                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40568                                 var varName = getUnusedName(name, symbol);
40569                                 addResult(ts.createImportEqualsDeclaration(
40570                                 /*decorators*/ undefined, 
40571                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40572                                 serializeExportSpecifier(name, varName);
40573                             }
40574                         }
40575                         context.tracker.trackSymbol = oldTrack;
40576                     }
40577                     else {
40578                         // serialize as an anonymous property declaration
40579                         var varName = getUnusedName(name, symbol);
40580                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40581                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40582                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40583                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40584                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40585                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40586                         }
40587                         else {
40588                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40589                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40590                             ], 2 /* Const */));
40591                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40592                         }
40593                         if (isExportAssignment) {
40594                             results.push(ts.createExportAssignment(
40595                             /*decorators*/ undefined, 
40596                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40597                         }
40598                         else if (name !== varName) {
40599                             serializeExportSpecifier(name, varName);
40600                         }
40601                     }
40602                 }
40603                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40604                     // Only object types which are not constructable, or indexable, whose members all come from the
40605                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40606                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40607                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40608                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40609                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40610                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40611                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40612                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40613                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40614                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40615                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40616                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40617                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40618                 }
40619                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40620                     return function serializePropertySymbol(p, isStatic, baseType) {
40621                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40622                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40623                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40624                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40625                             // need to be merged namespace members
40626                             return [];
40627                         }
40628                         if (p.flags & 4194304 /* Prototype */ ||
40629                             (baseType && getPropertyOfType(baseType, p.escapedName)
40630                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40631                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40632                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40633                             return [];
40634                         }
40635                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40636                         var name = getPropertyNameNodeForSymbol(p, context);
40637                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40638                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40639                             var result = [];
40640                             if (p.flags & 65536 /* SetAccessor */) {
40641                                 result.push(ts.setTextRange(ts.createSetAccessor(
40642                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40643                                     /*decorators*/ undefined, 
40644                                     /*modifiers*/ undefined, 
40645                                     /*dotDotDotToken*/ undefined, "arg", 
40646                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40647                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40648                             }
40649                             if (p.flags & 32768 /* GetAccessor */) {
40650                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40651                                 result.push(ts.setTextRange(ts.createGetAccessor(
40652                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40653                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40654                             }
40655                             return result;
40656                         }
40657                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40658                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40659                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40660                             return ts.setTextRange(createProperty(
40661                             /*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), 
40662                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40663                             // interface members can't have initializers, however class members _can_
40664                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40665                         }
40666                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40667                             var type = getTypeOfSymbol(p);
40668                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40669                             if (flag & 8 /* Private */) {
40670                                 return ts.setTextRange(createProperty(
40671                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40672                                 /*type*/ undefined, 
40673                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40674                             }
40675                             var results_1 = [];
40676                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40677                                 var sig = signatures_3[_i];
40678                                 // Each overload becomes a separate method declaration, in order
40679                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40680                                 decl.name = name; // TODO: Clone
40681                                 if (flag) {
40682                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40683                                 }
40684                                 if (p.flags & 16777216 /* Optional */) {
40685                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40686                                 }
40687                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40688                             }
40689                             return results_1;
40690                         }
40691                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40692                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40693                     };
40694                 }
40695                 function serializePropertySymbolForInterface(p, baseType) {
40696                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40697                 }
40698                 function serializeSignatures(kind, input, baseType, outputKind) {
40699                     var signatures = getSignaturesOfType(input, kind);
40700                     if (kind === 1 /* Construct */) {
40701                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40702                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40703                         }
40704                         if (baseType) {
40705                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40706                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40707                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40708                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40709                             }
40710                             if (baseSigs.length === signatures.length) {
40711                                 var failed = false;
40712                                 for (var i = 0; i < baseSigs.length; i++) {
40713                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40714                                         failed = true;
40715                                         break;
40716                                     }
40717                                 }
40718                                 if (!failed) {
40719                                     return []; // Every signature was identical - elide constructor list as it is inherited
40720                                 }
40721                             }
40722                         }
40723                         var privateProtected = 0;
40724                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40725                             var s = signatures_4[_i];
40726                             if (s.declaration) {
40727                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40728                             }
40729                         }
40730                         if (privateProtected) {
40731                             return [ts.setTextRange(ts.createConstructor(
40732                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40733                                 /*parameters*/ [], 
40734                                 /*body*/ undefined), signatures[0].declaration)];
40735                         }
40736                     }
40737                     var results = [];
40738                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40739                         var sig = signatures_5[_a];
40740                         // Each overload becomes a separate constructor declaration, in order
40741                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40742                         results.push(ts.setTextRange(decl, sig.declaration));
40743                     }
40744                     return results;
40745                 }
40746                 function serializeIndexSignatures(input, baseType) {
40747                     var results = [];
40748                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40749                         var type = _a[_i];
40750                         var info = getIndexInfoOfType(input, type);
40751                         if (info) {
40752                             if (baseType) {
40753                                 var baseInfo = getIndexInfoOfType(baseType, type);
40754                                 if (baseInfo) {
40755                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40756                                         continue; // elide identical index signatures
40757                                     }
40758                                 }
40759                             }
40760                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40761                         }
40762                     }
40763                     return results;
40764                 }
40765                 function serializeBaseType(t, staticType, rootName) {
40766                     var ref = trySerializeAsTypeReference(t);
40767                     if (ref) {
40768                         return ref;
40769                     }
40770                     var tempName = getUnusedName(rootName + "_base");
40771                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40772                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40773                     ], 2 /* Const */));
40774                     addResult(statement, 0 /* None */);
40775                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40776                 }
40777                 function trySerializeAsTypeReference(t) {
40778                     var typeArgs;
40779                     var reference;
40780                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40781                     // which we can't write out in a syntactically valid way as an expression
40782                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40783                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40784                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40785                     }
40786                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40787                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40788                     }
40789                     if (reference) {
40790                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40791                     }
40792                 }
40793                 function getUnusedName(input, symbol) {
40794                     if (symbol) {
40795                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40796                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40797                         }
40798                     }
40799                     if (symbol) {
40800                         input = getNameCandidateWorker(symbol, input);
40801                     }
40802                     var i = 0;
40803                     var original = input;
40804                     while (context.usedSymbolNames.has(input)) {
40805                         i++;
40806                         input = original + "_" + i;
40807                     }
40808                     context.usedSymbolNames.set(input, true);
40809                     if (symbol) {
40810                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40811                     }
40812                     return input;
40813                 }
40814                 function getNameCandidateWorker(symbol, localName) {
40815                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40816                         var flags = context.flags;
40817                         context.flags |= 16777216 /* InInitialEntityName */;
40818                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40819                         context.flags = flags;
40820                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40821                     }
40822                     if (localName === "default" /* Default */) {
40823                         localName = "_default";
40824                     }
40825                     else if (localName === "export=" /* ExportEquals */) {
40826                         localName = "_exports";
40827                     }
40828                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
40829                     return localName;
40830                 }
40831                 function getInternalSymbolName(symbol, localName) {
40832                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40833                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40834                     }
40835                     localName = getNameCandidateWorker(symbol, localName);
40836                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
40837                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
40838                     return localName;
40839                 }
40840             }
40841         }
40842         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
40843             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
40844             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
40845             function typePredicateToStringWorker(writer) {
40846                 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
40847                 );
40848                 var printer = ts.createPrinter({ removeComments: true });
40849                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
40850                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
40851                 return writer;
40852             }
40853         }
40854         function formatUnionTypes(types) {
40855             var result = [];
40856             var flags = 0;
40857             for (var i = 0; i < types.length; i++) {
40858                 var t = types[i];
40859                 flags |= t.flags;
40860                 if (!(t.flags & 98304 /* Nullable */)) {
40861                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
40862                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
40863                         if (baseType.flags & 1048576 /* Union */) {
40864                             var count = baseType.types.length;
40865                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
40866                                 result.push(baseType);
40867                                 i += count - 1;
40868                                 continue;
40869                             }
40870                         }
40871                     }
40872                     result.push(t);
40873                 }
40874             }
40875             if (flags & 65536 /* Null */)
40876                 result.push(nullType);
40877             if (flags & 32768 /* Undefined */)
40878                 result.push(undefinedType);
40879             return result || types;
40880         }
40881         function visibilityToString(flags) {
40882             if (flags === 8 /* Private */) {
40883                 return "private";
40884             }
40885             if (flags === 16 /* Protected */) {
40886                 return "protected";
40887             }
40888             return "public";
40889         }
40890         function getTypeAliasForTypeLiteral(type) {
40891             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
40892                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
40893                 if (node.kind === 247 /* TypeAliasDeclaration */) {
40894                     return getSymbolOfNode(node);
40895                 }
40896             }
40897             return undefined;
40898         }
40899         function isTopLevelInExternalModuleAugmentation(node) {
40900             return node && node.parent &&
40901                 node.parent.kind === 250 /* ModuleBlock */ &&
40902                 ts.isExternalModuleAugmentation(node.parent.parent);
40903         }
40904         function isDefaultBindingContext(location) {
40905             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
40906         }
40907         function getNameOfSymbolFromNameType(symbol, context) {
40908             var nameType = getSymbolLinks(symbol).nameType;
40909             if (nameType) {
40910                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
40911                     var name = "" + nameType.value;
40912                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
40913                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
40914                     }
40915                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
40916                         return "[" + name + "]";
40917                     }
40918                     return name;
40919                 }
40920                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
40921                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
40922                 }
40923             }
40924         }
40925         /**
40926          * Gets a human-readable name for a symbol.
40927          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
40928          *
40929          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
40930          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
40931          */
40932         function getNameOfSymbolAsWritten(symbol, context) {
40933             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
40934                 // If it's not the first part of an entity name, it must print as `default`
40935                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
40936                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
40937                     !symbol.declarations ||
40938                     // if not in the same binding context (source file, module declaration), it must print as `default`
40939                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
40940                 return "default";
40941             }
40942             if (symbol.declarations && symbol.declarations.length) {
40943                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
40944                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
40945                 if (declaration && name_2) {
40946                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
40947                         return ts.symbolName(symbol);
40948                     }
40949                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
40950                         var nameType = getSymbolLinks(symbol).nameType;
40951                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
40952                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
40953                             var result = getNameOfSymbolFromNameType(symbol, context);
40954                             if (result !== undefined) {
40955                                 return result;
40956                             }
40957                         }
40958                     }
40959                     return ts.declarationNameToString(name_2);
40960                 }
40961                 if (!declaration) {
40962                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
40963                 }
40964                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
40965                     return ts.declarationNameToString(declaration.parent.name);
40966                 }
40967                 switch (declaration.kind) {
40968                     case 214 /* ClassExpression */:
40969                     case 201 /* FunctionExpression */:
40970                     case 202 /* ArrowFunction */:
40971                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
40972                             context.encounteredError = true;
40973                         }
40974                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
40975                 }
40976             }
40977             var name = getNameOfSymbolFromNameType(symbol, context);
40978             return name !== undefined ? name : ts.symbolName(symbol);
40979         }
40980         function isDeclarationVisible(node) {
40981             if (node) {
40982                 var links = getNodeLinks(node);
40983                 if (links.isVisible === undefined) {
40984                     links.isVisible = !!determineIfDeclarationIsVisible();
40985                 }
40986                 return links.isVisible;
40987             }
40988             return false;
40989             function determineIfDeclarationIsVisible() {
40990                 switch (node.kind) {
40991                     case 315 /* JSDocCallbackTag */:
40992                     case 322 /* JSDocTypedefTag */:
40993                     case 316 /* JSDocEnumTag */:
40994                         // Top-level jsdoc type aliases are considered exported
40995                         // 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
40996                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
40997                     case 191 /* BindingElement */:
40998                         return isDeclarationVisible(node.parent.parent);
40999                     case 242 /* VariableDeclaration */:
41000                         if (ts.isBindingPattern(node.name) &&
41001                             !node.name.elements.length) {
41002                             // If the binding pattern is empty, this variable declaration is not visible
41003                             return false;
41004                         }
41005                     // falls through
41006                     case 249 /* ModuleDeclaration */:
41007                     case 245 /* ClassDeclaration */:
41008                     case 246 /* InterfaceDeclaration */:
41009                     case 247 /* TypeAliasDeclaration */:
41010                     case 244 /* FunctionDeclaration */:
41011                     case 248 /* EnumDeclaration */:
41012                     case 253 /* ImportEqualsDeclaration */:
41013                         // external module augmentation is always visible
41014                         if (ts.isExternalModuleAugmentation(node)) {
41015                             return true;
41016                         }
41017                         var parent = getDeclarationContainer(node);
41018                         // If the node is not exported or it is not ambient module element (except import declaration)
41019                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41020                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41021                             return isGlobalSourceFile(parent);
41022                         }
41023                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41024                         return isDeclarationVisible(parent);
41025                     case 159 /* PropertyDeclaration */:
41026                     case 158 /* PropertySignature */:
41027                     case 163 /* GetAccessor */:
41028                     case 164 /* SetAccessor */:
41029                     case 161 /* MethodDeclaration */:
41030                     case 160 /* MethodSignature */:
41031                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41032                             // Private/protected properties/methods are not visible
41033                             return false;
41034                         }
41035                     // Public properties/methods are visible if its parents are visible, so:
41036                     // falls through
41037                     case 162 /* Constructor */:
41038                     case 166 /* ConstructSignature */:
41039                     case 165 /* CallSignature */:
41040                     case 167 /* IndexSignature */:
41041                     case 156 /* Parameter */:
41042                     case 250 /* ModuleBlock */:
41043                     case 170 /* FunctionType */:
41044                     case 171 /* ConstructorType */:
41045                     case 173 /* TypeLiteral */:
41046                     case 169 /* TypeReference */:
41047                     case 174 /* ArrayType */:
41048                     case 175 /* TupleType */:
41049                     case 178 /* UnionType */:
41050                     case 179 /* IntersectionType */:
41051                     case 182 /* ParenthesizedType */:
41052                         return isDeclarationVisible(node.parent);
41053                     // Default binding, import specifier and namespace import is visible
41054                     // only on demand so by default it is not visible
41055                     case 255 /* ImportClause */:
41056                     case 256 /* NamespaceImport */:
41057                     case 258 /* ImportSpecifier */:
41058                         return false;
41059                     // Type parameters are always visible
41060                     case 155 /* TypeParameter */:
41061                     // Source file and namespace export are always visible
41062                     // falls through
41063                     case 290 /* SourceFile */:
41064                     case 252 /* NamespaceExportDeclaration */:
41065                         return true;
41066                     // Export assignments do not create name bindings outside the module
41067                     case 259 /* ExportAssignment */:
41068                         return false;
41069                     default:
41070                         return false;
41071                 }
41072             }
41073         }
41074         function collectLinkedAliases(node, setVisibility) {
41075             var exportSymbol;
41076             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41077                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41078             }
41079             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41080                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41081             }
41082             var result;
41083             var visited;
41084             if (exportSymbol) {
41085                 visited = ts.createMap();
41086                 visited.set("" + getSymbolId(exportSymbol), true);
41087                 buildVisibleNodeList(exportSymbol.declarations);
41088             }
41089             return result;
41090             function buildVisibleNodeList(declarations) {
41091                 ts.forEach(declarations, function (declaration) {
41092                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41093                     if (setVisibility) {
41094                         getNodeLinks(declaration).isVisible = true;
41095                     }
41096                     else {
41097                         result = result || [];
41098                         ts.pushIfUnique(result, resultNode);
41099                     }
41100                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41101                         // Add the referenced top container visible
41102                         var internalModuleReference = declaration.moduleReference;
41103                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41104                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41105                         var id = importSymbol && "" + getSymbolId(importSymbol);
41106                         if (importSymbol && !visited.has(id)) {
41107                             visited.set(id, true);
41108                             buildVisibleNodeList(importSymbol.declarations);
41109                         }
41110                     }
41111                 });
41112             }
41113         }
41114         /**
41115          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41116          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41117          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41118          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41119          * In order to see if the same query has already been done before, the target object and the propertyName both
41120          * must match the one passed in.
41121          *
41122          * @param target The symbol, type, or signature whose type is being queried
41123          * @param propertyName The property name that should be used to query the target for its type
41124          */
41125         function pushTypeResolution(target, propertyName) {
41126             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41127             if (resolutionCycleStartIndex >= 0) {
41128                 // A cycle was found
41129                 var length_3 = resolutionTargets.length;
41130                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41131                     resolutionResults[i] = false;
41132                 }
41133                 return false;
41134             }
41135             resolutionTargets.push(target);
41136             resolutionResults.push(/*items*/ true);
41137             resolutionPropertyNames.push(propertyName);
41138             return true;
41139         }
41140         function findResolutionCycleStartIndex(target, propertyName) {
41141             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41142                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41143                     return -1;
41144                 }
41145                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41146                     return i;
41147                 }
41148             }
41149             return -1;
41150         }
41151         function hasType(target, propertyName) {
41152             switch (propertyName) {
41153                 case 0 /* Type */:
41154                     return !!getSymbolLinks(target).type;
41155                 case 5 /* EnumTagType */:
41156                     return !!(getNodeLinks(target).resolvedEnumType);
41157                 case 2 /* DeclaredType */:
41158                     return !!getSymbolLinks(target).declaredType;
41159                 case 1 /* ResolvedBaseConstructorType */:
41160                     return !!target.resolvedBaseConstructorType;
41161                 case 3 /* ResolvedReturnType */:
41162                     return !!target.resolvedReturnType;
41163                 case 4 /* ImmediateBaseConstraint */:
41164                     return !!target.immediateBaseConstraint;
41165                 case 6 /* ResolvedTypeArguments */:
41166                     return !!target.resolvedTypeArguments;
41167             }
41168             return ts.Debug.assertNever(propertyName);
41169         }
41170         /**
41171          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41172          * be true if no circularities were detected, or false if a circularity was found.
41173          */
41174         function popTypeResolution() {
41175             resolutionTargets.pop();
41176             resolutionPropertyNames.pop();
41177             return resolutionResults.pop();
41178         }
41179         function getDeclarationContainer(node) {
41180             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41181                 switch (node.kind) {
41182                     case 242 /* VariableDeclaration */:
41183                     case 243 /* VariableDeclarationList */:
41184                     case 258 /* ImportSpecifier */:
41185                     case 257 /* NamedImports */:
41186                     case 256 /* NamespaceImport */:
41187                     case 255 /* ImportClause */:
41188                         return false;
41189                     default:
41190                         return true;
41191                 }
41192             }).parent;
41193         }
41194         function getTypeOfPrototypeProperty(prototype) {
41195             // TypeScript 1.0 spec (April 2014): 8.4
41196             // Every class automatically contains a static property member named 'prototype',
41197             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41198             // It is an error to explicitly declare a static property member with the name 'prototype'.
41199             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41200             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41201         }
41202         // Return the type of the given property in the given type, or undefined if no such property exists
41203         function getTypeOfPropertyOfType(type, name) {
41204             var prop = getPropertyOfType(type, name);
41205             return prop ? getTypeOfSymbol(prop) : undefined;
41206         }
41207         function getTypeOfPropertyOrIndexSignature(type, name) {
41208             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41209         }
41210         function isTypeAny(type) {
41211             return type && (type.flags & 1 /* Any */) !== 0;
41212         }
41213         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41214         // assigned by contextual typing.
41215         function getTypeForBindingElementParent(node) {
41216             var symbol = getSymbolOfNode(node);
41217             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41218         }
41219         function getRestType(source, properties, symbol) {
41220             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41221             if (source.flags & 131072 /* Never */) {
41222                 return emptyObjectType;
41223             }
41224             if (source.flags & 1048576 /* Union */) {
41225                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41226             }
41227             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41228             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41229                 if (omitKeyType.flags & 131072 /* Never */) {
41230                     return source;
41231                 }
41232                 var omitTypeAlias = getGlobalOmitSymbol();
41233                 if (!omitTypeAlias) {
41234                     return errorType;
41235                 }
41236                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41237             }
41238             var members = ts.createSymbolTable();
41239             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41240                 var prop = _a[_i];
41241                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41242                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41243                     && isSpreadableProperty(prop)) {
41244                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41245                 }
41246             }
41247             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41248             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41249             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41250             result.objectFlags |= 131072 /* ObjectRestType */;
41251             return result;
41252         }
41253         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41254         // forms of destructuring are possible:
41255         //   let { x } = obj;  // BindingElement
41256         //   let [ x ] = obj;  // BindingElement
41257         //   { x } = obj;      // ShorthandPropertyAssignment
41258         //   { x: v } = obj;   // PropertyAssignment
41259         //   [ x ] = obj;      // Expression
41260         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41261         // flow analyzer doesn't have to handle all the different syntactic forms.
41262         function getFlowTypeOfDestructuring(node, declaredType) {
41263             var reference = getSyntheticElementAccess(node);
41264             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41265         }
41266         function getSyntheticElementAccess(node) {
41267             var parentAccess = getParentElementAccess(node);
41268             if (parentAccess && parentAccess.flowNode) {
41269                 var propName = getDestructuringPropertyName(node);
41270                 if (propName) {
41271                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41272                     result.parent = node;
41273                     result.expression = parentAccess;
41274                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41275                     literal.parent = result;
41276                     literal.text = propName;
41277                     result.argumentExpression = literal;
41278                     result.flowNode = parentAccess.flowNode;
41279                     return result;
41280                 }
41281             }
41282         }
41283         function getParentElementAccess(node) {
41284             var ancestor = node.parent.parent;
41285             switch (ancestor.kind) {
41286                 case 191 /* BindingElement */:
41287                 case 281 /* PropertyAssignment */:
41288                     return getSyntheticElementAccess(ancestor);
41289                 case 192 /* ArrayLiteralExpression */:
41290                     return getSyntheticElementAccess(node.parent);
41291                 case 242 /* VariableDeclaration */:
41292                     return ancestor.initializer;
41293                 case 209 /* BinaryExpression */:
41294                     return ancestor.right;
41295             }
41296         }
41297         function getDestructuringPropertyName(node) {
41298             var parent = node.parent;
41299             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41300                 return getLiteralPropertyNameText(node.propertyName || node.name);
41301             }
41302             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41303                 return getLiteralPropertyNameText(node.name);
41304             }
41305             return "" + parent.elements.indexOf(node);
41306         }
41307         function getLiteralPropertyNameText(name) {
41308             var type = getLiteralTypeFromPropertyName(name);
41309             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41310         }
41311         /** Return the inferred type for a binding element */
41312         function getTypeForBindingElement(declaration) {
41313             var pattern = declaration.parent;
41314             var parentType = getTypeForBindingElementParent(pattern.parent);
41315             // If no type or an any type was inferred for parent, infer that for the binding element
41316             if (!parentType || isTypeAny(parentType)) {
41317                 return parentType;
41318             }
41319             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41320             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41321                 parentType = getNonNullableType(parentType);
41322             }
41323             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41324             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41325                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41326             }
41327             var type;
41328             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41329                 if (declaration.dotDotDotToken) {
41330                     parentType = getReducedType(parentType);
41331                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41332                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41333                         return errorType;
41334                     }
41335                     var literalMembers = [];
41336                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41337                         var element = _a[_i];
41338                         if (!element.dotDotDotToken) {
41339                             literalMembers.push(element.propertyName || element.name);
41340                         }
41341                     }
41342                     type = getRestType(parentType, literalMembers, declaration.symbol);
41343                 }
41344                 else {
41345                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41346                     var name = declaration.propertyName || declaration.name;
41347                     var indexType = getLiteralTypeFromPropertyName(name);
41348                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41349                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41350                 }
41351             }
41352             else {
41353                 // This elementType will be used if the specific property corresponding to this index is not
41354                 // present (aka the tuple element property). This call also checks that the parentType is in
41355                 // fact an iterable or array (depending on target language).
41356                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41357                 var index_1 = pattern.elements.indexOf(declaration);
41358                 if (declaration.dotDotDotToken) {
41359                     // If the parent is a tuple type, the rest element has a tuple type of the
41360                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41361                     // element type as the parent type.
41362                     type = everyType(parentType, isTupleType) ?
41363                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41364                         createArrayType(elementType);
41365                 }
41366                 else if (isArrayLikeType(parentType)) {
41367                     var indexType = getLiteralType(index_1);
41368                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41369                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41370                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41371                 }
41372                 else {
41373                     type = elementType;
41374                 }
41375             }
41376             if (!declaration.initializer) {
41377                 return type;
41378             }
41379             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41380                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41381                 // undefined from the final type.
41382                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41383                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41384                     type;
41385             }
41386             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41387         }
41388         function getTypeForDeclarationFromJSDocComment(declaration) {
41389             var jsdocType = ts.getJSDocType(declaration);
41390             if (jsdocType) {
41391                 return getTypeFromTypeNode(jsdocType);
41392             }
41393             return undefined;
41394         }
41395         function isNullOrUndefined(node) {
41396             var expr = ts.skipParentheses(node);
41397             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41398         }
41399         function isEmptyArrayLiteral(node) {
41400             var expr = ts.skipParentheses(node);
41401             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41402         }
41403         function addOptionality(type, optional) {
41404             if (optional === void 0) { optional = true; }
41405             return strictNullChecks && optional ? getOptionalType(type) : type;
41406         }
41407         // Return the inferred type for a variable, parameter, or property declaration
41408         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41409             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41410             // right hand expression is of a type parameter type.
41411             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41412                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41413                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41414             }
41415             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41416                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41417                 // missing properties/signatures required to get its iteratedType (like
41418                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41419                 // or it may have led to an error inside getElementTypeOfIterable.
41420                 var forOfStatement = declaration.parent.parent;
41421                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41422             }
41423             if (ts.isBindingPattern(declaration.parent)) {
41424                 return getTypeForBindingElement(declaration);
41425             }
41426             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41427                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41428             // Use type from type annotation if one is present
41429             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41430             if (declaredType) {
41431                 return addOptionality(declaredType, isOptional);
41432             }
41433             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41434                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41435                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41436                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41437                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41438                 // initializer or a 'null' or 'undefined' initializer.
41439                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41440                     return autoType;
41441                 }
41442                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41443                 // literal initializer.
41444                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41445                     return autoArrayType;
41446                 }
41447             }
41448             if (declaration.kind === 156 /* Parameter */) {
41449                 var func = declaration.parent;
41450                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41451                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41452                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41453                     if (getter) {
41454                         var getterSignature = getSignatureFromDeclaration(getter);
41455                         var thisParameter = getAccessorThisParameter(func);
41456                         if (thisParameter && declaration === thisParameter) {
41457                             // Use the type from the *getter*
41458                             ts.Debug.assert(!thisParameter.type);
41459                             return getTypeOfSymbol(getterSignature.thisParameter);
41460                         }
41461                         return getReturnTypeOfSignature(getterSignature);
41462                     }
41463                 }
41464                 if (ts.isInJSFile(declaration)) {
41465                     var typeTag = ts.getJSDocType(func);
41466                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41467                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41468                     }
41469                 }
41470                 // Use contextual parameter type if one is available
41471                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41472                 if (type) {
41473                     return addOptionality(type, isOptional);
41474                 }
41475             }
41476             else if (ts.isInJSFile(declaration)) {
41477                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41478                 if (containerObjectType) {
41479                     return containerObjectType;
41480                 }
41481             }
41482             // Use the type of the initializer expression if one is present and the declaration is
41483             // not a parameter of a contextually typed function
41484             if (declaration.initializer) {
41485                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41486                 return addOptionality(type, isOptional);
41487             }
41488             if (ts.isJsxAttribute(declaration)) {
41489                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41490                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41491                 return trueType;
41492             }
41493             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41494             // typed function, use the type implied by the binding pattern
41495             if (ts.isBindingPattern(declaration.name)) {
41496                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41497             }
41498             // No type specified and nothing can be inferred
41499             return undefined;
41500         }
41501         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41502             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41503             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41504             if (container) {
41505                 var tag = ts.getJSDocTypeTag(container);
41506                 if (tag && tag.typeExpression) {
41507                     return getTypeFromTypeNode(tag.typeExpression);
41508                 }
41509                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41510                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41511             }
41512             var definedInConstructor = false;
41513             var definedInMethod = false;
41514             var jsdocType;
41515             var types;
41516             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41517                 var declaration = _a[_i];
41518                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41519                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41520                         undefined;
41521                 if (!expression) {
41522                     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
41523                 }
41524                 var kind = ts.isAccessExpression(expression)
41525                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41526                     : ts.getAssignmentDeclarationKind(expression);
41527                 if (kind === 4 /* ThisProperty */) {
41528                     if (isDeclarationInConstructor(expression)) {
41529                         definedInConstructor = true;
41530                     }
41531                     else {
41532                         definedInMethod = true;
41533                     }
41534                 }
41535                 if (!ts.isCallExpression(expression)) {
41536                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41537                 }
41538                 if (!jsdocType) {
41539                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41540                 }
41541             }
41542             var type = jsdocType;
41543             if (!type) {
41544                 if (!ts.length(types)) {
41545                     return errorType; // No types from any declarations :(
41546                 }
41547                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41548                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41549                 if (definedInMethod) {
41550                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41551                     if (propType) {
41552                         (constructorTypes || (constructorTypes = [])).push(propType);
41553                         definedInConstructor = true;
41554                     }
41555                 }
41556                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41557                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41558             }
41559             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41560             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41561                 reportImplicitAny(symbol.valueDeclaration, anyType);
41562                 return anyType;
41563             }
41564             return widened;
41565         }
41566         function getJSContainerObjectType(decl, symbol, init) {
41567             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41568                 return undefined;
41569             }
41570             var exports = ts.createSymbolTable();
41571             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41572                 var s_2 = getSymbolOfNode(decl);
41573                 if (s_2 && ts.hasEntries(s_2.exports)) {
41574                     mergeSymbolTable(exports, s_2.exports);
41575                 }
41576                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41577             }
41578             var s = getSymbolOfNode(decl);
41579             if (s && ts.hasEntries(s.exports)) {
41580                 mergeSymbolTable(exports, s.exports);
41581             }
41582             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41583             type.objectFlags |= 16384 /* JSLiteral */;
41584             return type;
41585         }
41586         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41587             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41588             if (typeNode) {
41589                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41590                 if (!declaredType) {
41591                     return type;
41592                 }
41593                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41594                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41595                 }
41596             }
41597             if (symbol.parent) {
41598                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41599                 if (typeNode_2) {
41600                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41601                 }
41602             }
41603             return declaredType;
41604         }
41605         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41606         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41607             if (ts.isCallExpression(expression)) {
41608                 if (resolvedSymbol) {
41609                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41610                 }
41611                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41612                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41613                 if (valueType) {
41614                     return valueType;
41615                 }
41616                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41617                 if (getFunc) {
41618                     var getSig = getSingleCallSignature(getFunc);
41619                     if (getSig) {
41620                         return getReturnTypeOfSignature(getSig);
41621                     }
41622                 }
41623                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41624                 if (setFunc) {
41625                     var setSig = getSingleCallSignature(setFunc);
41626                     if (setSig) {
41627                         return getTypeOfFirstParameterOfSignature(setSig);
41628                     }
41629                 }
41630                 return anyType;
41631             }
41632             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41633                 return anyType;
41634             }
41635             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41636             if (type.flags & 524288 /* Object */ &&
41637                 kind === 2 /* ModuleExports */ &&
41638                 symbol.escapedName === "export=" /* ExportEquals */) {
41639                 var exportedType = resolveStructuredTypeMembers(type);
41640                 var members_4 = ts.createSymbolTable();
41641                 ts.copyEntries(exportedType.members, members_4);
41642                 if (resolvedSymbol && !resolvedSymbol.exports) {
41643                     resolvedSymbol.exports = ts.createSymbolTable();
41644                 }
41645                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41646                     var _a;
41647                     var exportedMember = members_4.get(name);
41648                     if (exportedMember && exportedMember !== s) {
41649                         if (s.flags & 111551 /* Value */) {
41650                             // If the member has an additional value-like declaration, union the types from the two declarations,
41651                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41652                             // a pattern like:
41653                             //
41654                             // module.exports = { a: true };
41655                             // module.exports.a = 3;
41656                             //
41657                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41658                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41659                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41660                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41661                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41662                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41663                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41664                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41665                             }
41666                             var union = createSymbol(s.flags | exportedMember.flags, name);
41667                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41668                             union.valueDeclaration = exportedMember.valueDeclaration;
41669                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41670                             members_4.set(name, union);
41671                         }
41672                         else {
41673                             members_4.set(name, mergeSymbol(s, exportedMember));
41674                         }
41675                     }
41676                     else {
41677                         members_4.set(name, s);
41678                     }
41679                 });
41680                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41681                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41682                 return result;
41683             }
41684             if (isEmptyArrayLiteralType(type)) {
41685                 reportImplicitAny(expression, anyArrayType);
41686                 return anyArrayType;
41687             }
41688             return type;
41689         }
41690         function containsSameNamedThisProperty(thisProperty, expression) {
41691             return ts.isPropertyAccessExpression(thisProperty)
41692                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41693                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41694         }
41695         function isDeclarationInConstructor(expression) {
41696             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41697             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41698             // Function expressions that are assigned to the prototype count as methods.
41699             return thisContainer.kind === 162 /* Constructor */ ||
41700                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41701                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41702         }
41703         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41704             ts.Debug.assert(types.length === declarations.length);
41705             return types.filter(function (_, i) {
41706                 var declaration = declarations[i];
41707                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41708                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41709                 return expression && isDeclarationInConstructor(expression);
41710             });
41711         }
41712         /** check for definition in base class if any declaration is in a class */
41713         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41714             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41715                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41716                 return ts.isClassLike(parent) && parent;
41717             });
41718             if (parentDeclaration) {
41719                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41720                 var baseClassType = classType && getBaseTypes(classType)[0];
41721                 if (baseClassType) {
41722                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41723                 }
41724             }
41725         }
41726         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41727         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41728         // pattern. Otherwise, it is the type any.
41729         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41730             if (element.initializer) {
41731                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41732                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41733                 // pattern.
41734                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41735                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41736             }
41737             if (ts.isBindingPattern(element.name)) {
41738                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41739             }
41740             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41741                 reportImplicitAny(element, anyType);
41742             }
41743             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41744             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41745             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41746             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41747             return includePatternInType ? nonInferrableAnyType : anyType;
41748         }
41749         // Return the type implied by an object binding pattern
41750         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41751             var members = ts.createSymbolTable();
41752             var stringIndexInfo;
41753             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41754             ts.forEach(pattern.elements, function (e) {
41755                 var name = e.propertyName || e.name;
41756                 if (e.dotDotDotToken) {
41757                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41758                     return;
41759                 }
41760                 var exprType = getLiteralTypeFromPropertyName(name);
41761                 if (!isTypeUsableAsPropertyName(exprType)) {
41762                     // do not include computed properties in the implied type
41763                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41764                     return;
41765                 }
41766                 var text = getPropertyNameFromType(exprType);
41767                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41768                 var symbol = createSymbol(flags, text);
41769                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41770                 symbol.bindingElement = e;
41771                 members.set(symbol.escapedName, symbol);
41772             });
41773             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41774             result.objectFlags |= objectFlags;
41775             if (includePatternInType) {
41776                 result.pattern = pattern;
41777                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41778             }
41779             return result;
41780         }
41781         // Return the type implied by an array binding pattern
41782         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41783             var elements = pattern.elements;
41784             var lastElement = ts.lastOrUndefined(elements);
41785             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41786             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41787                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41788             }
41789             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41790             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41791             var result = createTupleType(elementTypes, minLength, hasRestElement);
41792             if (includePatternInType) {
41793                 result = cloneTypeReference(result);
41794                 result.pattern = pattern;
41795                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41796             }
41797             return result;
41798         }
41799         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41800         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41801         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41802         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41803         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41804         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41805         // the parameter.
41806         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41807             if (includePatternInType === void 0) { includePatternInType = false; }
41808             if (reportErrors === void 0) { reportErrors = false; }
41809             return pattern.kind === 189 /* ObjectBindingPattern */
41810                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41811                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41812         }
41813         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41814         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41815         // is a bit more involved. For example:
41816         //
41817         //   var [x, s = ""] = [1, "one"];
41818         //
41819         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41820         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41821         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41822         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41823             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
41824         }
41825         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
41826             if (type) {
41827                 if (reportErrors) {
41828                     reportErrorsFromWidening(declaration, type);
41829                 }
41830                 // always widen a 'unique symbol' type if the type was created for a different declaration.
41831                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
41832                     type = esSymbolType;
41833                 }
41834                 return getWidenedType(type);
41835             }
41836             // Rest parameters default to type any[], other parameters default to type any
41837             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
41838             // Report implicit any errors unless this is a private property within an ambient declaration
41839             if (reportErrors) {
41840                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
41841                     reportImplicitAny(declaration, type);
41842                 }
41843             }
41844             return type;
41845         }
41846         function declarationBelongsToPrivateAmbientMember(declaration) {
41847             var root = ts.getRootDeclaration(declaration);
41848             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
41849             return isPrivateWithinAmbient(memberDeclaration);
41850         }
41851         function tryGetTypeFromEffectiveTypeNode(declaration) {
41852             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
41853             if (typeNode) {
41854                 return getTypeFromTypeNode(typeNode);
41855             }
41856         }
41857         function getTypeOfVariableOrParameterOrProperty(symbol) {
41858             var links = getSymbolLinks(symbol);
41859             if (!links.type) {
41860                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
41861                 // For a contextually typed parameter it is possible that a type has already
41862                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
41863                 // to preserve this type.
41864                 if (!links.type) {
41865                     links.type = type;
41866                 }
41867             }
41868             return links.type;
41869         }
41870         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
41871             // Handle prototype property
41872             if (symbol.flags & 4194304 /* Prototype */) {
41873                 return getTypeOfPrototypeProperty(symbol);
41874             }
41875             // CommonsJS require and module both have type any.
41876             if (symbol === requireSymbol) {
41877                 return anyType;
41878             }
41879             if (symbol.flags & 134217728 /* ModuleExports */) {
41880                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
41881                 var members = ts.createSymbolTable();
41882                 members.set("exports", fileSymbol);
41883                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
41884             }
41885             // Handle catch clause variables
41886             var declaration = symbol.valueDeclaration;
41887             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
41888                 return anyType;
41889             }
41890             // Handle export default expressions
41891             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
41892                 if (!declaration.statements.length) {
41893                     return emptyObjectType;
41894                 }
41895                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
41896             }
41897             // Handle variable, parameter or property
41898             if (!pushTypeResolution(symbol, 0 /* Type */)) {
41899                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41900                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41901                     return getTypeOfFuncClassEnumModule(symbol);
41902                 }
41903                 return reportCircularityError(symbol);
41904             }
41905             var type;
41906             if (declaration.kind === 259 /* ExportAssignment */) {
41907                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
41908             }
41909             else if (ts.isBinaryExpression(declaration) ||
41910                 (ts.isInJSFile(declaration) &&
41911                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
41912                 type = getWidenedTypeForAssignmentDeclaration(symbol);
41913             }
41914             else if (ts.isJSDocPropertyLikeTag(declaration)
41915                 || ts.isPropertyAccessExpression(declaration)
41916                 || ts.isElementAccessExpression(declaration)
41917                 || ts.isIdentifier(declaration)
41918                 || ts.isStringLiteralLike(declaration)
41919                 || ts.isNumericLiteral(declaration)
41920                 || ts.isClassDeclaration(declaration)
41921                 || ts.isFunctionDeclaration(declaration)
41922                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
41923                 || ts.isMethodSignature(declaration)
41924                 || ts.isSourceFile(declaration)) {
41925                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41926                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
41927                     return getTypeOfFuncClassEnumModule(symbol);
41928                 }
41929                 type = ts.isBinaryExpression(declaration.parent) ?
41930                     getWidenedTypeForAssignmentDeclaration(symbol) :
41931                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
41932             }
41933             else if (ts.isPropertyAssignment(declaration)) {
41934                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
41935             }
41936             else if (ts.isJsxAttribute(declaration)) {
41937                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
41938             }
41939             else if (ts.isShorthandPropertyAssignment(declaration)) {
41940                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
41941             }
41942             else if (ts.isObjectLiteralMethod(declaration)) {
41943                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
41944             }
41945             else if (ts.isParameter(declaration)
41946                 || ts.isPropertyDeclaration(declaration)
41947                 || ts.isPropertySignature(declaration)
41948                 || ts.isVariableDeclaration(declaration)
41949                 || ts.isBindingElement(declaration)) {
41950                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
41951             }
41952             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
41953             // Re-dispatch based on valueDeclaration.kind instead.
41954             else if (ts.isEnumDeclaration(declaration)) {
41955                 type = getTypeOfFuncClassEnumModule(symbol);
41956             }
41957             else if (ts.isEnumMember(declaration)) {
41958                 type = getTypeOfEnumMember(symbol);
41959             }
41960             else if (ts.isAccessor(declaration)) {
41961                 type = resolveTypeOfAccessors(symbol);
41962             }
41963             else {
41964                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
41965             }
41966             if (!popTypeResolution()) {
41967                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41968                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41969                     return getTypeOfFuncClassEnumModule(symbol);
41970                 }
41971                 return reportCircularityError(symbol);
41972             }
41973             return type;
41974         }
41975         function getAnnotatedAccessorTypeNode(accessor) {
41976             if (accessor) {
41977                 if (accessor.kind === 163 /* GetAccessor */) {
41978                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
41979                     return getterTypeAnnotation;
41980                 }
41981                 else {
41982                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
41983                     return setterTypeAnnotation;
41984                 }
41985             }
41986             return undefined;
41987         }
41988         function getAnnotatedAccessorType(accessor) {
41989             var node = getAnnotatedAccessorTypeNode(accessor);
41990             return node && getTypeFromTypeNode(node);
41991         }
41992         function getAnnotatedAccessorThisParameter(accessor) {
41993             var parameter = getAccessorThisParameter(accessor);
41994             return parameter && parameter.symbol;
41995         }
41996         function getThisTypeOfDeclaration(declaration) {
41997             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
41998         }
41999         function getTypeOfAccessors(symbol) {
42000             var links = getSymbolLinks(symbol);
42001             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42002         }
42003         function getTypeOfAccessorsWorker(symbol) {
42004             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42005                 return errorType;
42006             }
42007             var type = resolveTypeOfAccessors(symbol);
42008             if (!popTypeResolution()) {
42009                 type = anyType;
42010                 if (noImplicitAny) {
42011                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42012                     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));
42013                 }
42014             }
42015             return type;
42016         }
42017         function resolveTypeOfAccessors(symbol) {
42018             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42019             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42020             if (getter && ts.isInJSFile(getter)) {
42021                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42022                 if (jsDocType) {
42023                     return jsDocType;
42024                 }
42025             }
42026             // First try to see if the user specified a return type on the get-accessor.
42027             var getterReturnType = getAnnotatedAccessorType(getter);
42028             if (getterReturnType) {
42029                 return getterReturnType;
42030             }
42031             else {
42032                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42033                 var setterParameterType = getAnnotatedAccessorType(setter);
42034                 if (setterParameterType) {
42035                     return setterParameterType;
42036                 }
42037                 else {
42038                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42039                     if (getter && getter.body) {
42040                         return getReturnTypeFromBody(getter);
42041                     }
42042                     // Otherwise, fall back to 'any'.
42043                     else {
42044                         if (setter) {
42045                             if (!isPrivateWithinAmbient(setter)) {
42046                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42047                             }
42048                         }
42049                         else {
42050                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42051                             if (!isPrivateWithinAmbient(getter)) {
42052                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42053                             }
42054                         }
42055                         return anyType;
42056                     }
42057                 }
42058             }
42059         }
42060         function getBaseTypeVariableOfClass(symbol) {
42061             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42062             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42063                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42064                     undefined;
42065         }
42066         function getTypeOfFuncClassEnumModule(symbol) {
42067             var links = getSymbolLinks(symbol);
42068             var originalLinks = links;
42069             if (!links.type) {
42070                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42071                 if (jsDeclaration) {
42072                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42073                     if (merged) {
42074                         // note:we overwrite links because we just cloned the symbol
42075                         symbol = links = merged;
42076                     }
42077                 }
42078                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42079             }
42080             return links.type;
42081         }
42082         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42083             var declaration = symbol.valueDeclaration;
42084             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42085                 return anyType;
42086             }
42087             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42088                 ts.isAccessExpression(declaration) &&
42089                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42090                 return getWidenedTypeForAssignmentDeclaration(symbol);
42091             }
42092             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42093                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42094                 if (resolvedModule !== symbol) {
42095                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42096                         return errorType;
42097                     }
42098                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42099                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42100                     if (!popTypeResolution()) {
42101                         return reportCircularityError(symbol);
42102                     }
42103                     return type_1;
42104                 }
42105             }
42106             var type = createObjectType(16 /* Anonymous */, symbol);
42107             if (symbol.flags & 32 /* Class */) {
42108                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42109                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42110             }
42111             else {
42112                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42113             }
42114         }
42115         function getTypeOfEnumMember(symbol) {
42116             var links = getSymbolLinks(symbol);
42117             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42118         }
42119         function getTypeOfAlias(symbol) {
42120             var links = getSymbolLinks(symbol);
42121             if (!links.type) {
42122                 var targetSymbol = resolveAlias(symbol);
42123                 // It only makes sense to get the type of a value symbol. If the result of resolving
42124                 // the alias is not a value, then it has no type. To get the type associated with a
42125                 // type symbol, call getDeclaredTypeOfSymbol.
42126                 // This check is important because without it, a call to getTypeOfSymbol could end
42127                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42128                 links.type = targetSymbol.flags & 111551 /* Value */
42129                     ? getTypeOfSymbol(targetSymbol)
42130                     : errorType;
42131             }
42132             return links.type;
42133         }
42134         function getTypeOfInstantiatedSymbol(symbol) {
42135             var links = getSymbolLinks(symbol);
42136             if (!links.type) {
42137                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42138                     return links.type = errorType;
42139                 }
42140                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42141                 if (!popTypeResolution()) {
42142                     type = reportCircularityError(symbol);
42143                 }
42144                 links.type = type;
42145             }
42146             return links.type;
42147         }
42148         function reportCircularityError(symbol) {
42149             var declaration = symbol.valueDeclaration;
42150             // Check if variable has type annotation that circularly references the variable itself
42151             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42152                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42153                 return errorType;
42154             }
42155             // Check if variable has initializer that circularly references the variable itself
42156             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42157                 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));
42158             }
42159             // Circularities could also result from parameters in function expressions that end up
42160             // having themselves as contextual types following type argument inference. In those cases
42161             // we have already reported an implicit any error so we don't report anything here.
42162             return anyType;
42163         }
42164         function getTypeOfSymbolWithDeferredType(symbol) {
42165             var links = getSymbolLinks(symbol);
42166             if (!links.type) {
42167                 ts.Debug.assertIsDefined(links.deferralParent);
42168                 ts.Debug.assertIsDefined(links.deferralConstituents);
42169                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42170             }
42171             return links.type;
42172         }
42173         function getTypeOfSymbol(symbol) {
42174             var checkFlags = ts.getCheckFlags(symbol);
42175             if (checkFlags & 65536 /* DeferredType */) {
42176                 return getTypeOfSymbolWithDeferredType(symbol);
42177             }
42178             if (checkFlags & 1 /* Instantiated */) {
42179                 return getTypeOfInstantiatedSymbol(symbol);
42180             }
42181             if (checkFlags & 262144 /* Mapped */) {
42182                 return getTypeOfMappedSymbol(symbol);
42183             }
42184             if (checkFlags & 8192 /* ReverseMapped */) {
42185                 return getTypeOfReverseMappedSymbol(symbol);
42186             }
42187             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42188                 return getTypeOfVariableOrParameterOrProperty(symbol);
42189             }
42190             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42191                 return getTypeOfFuncClassEnumModule(symbol);
42192             }
42193             if (symbol.flags & 8 /* EnumMember */) {
42194                 return getTypeOfEnumMember(symbol);
42195             }
42196             if (symbol.flags & 98304 /* Accessor */) {
42197                 return getTypeOfAccessors(symbol);
42198             }
42199             if (symbol.flags & 2097152 /* Alias */) {
42200                 return getTypeOfAlias(symbol);
42201             }
42202             return errorType;
42203         }
42204         function isReferenceToType(type, target) {
42205             return type !== undefined
42206                 && target !== undefined
42207                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42208                 && type.target === target;
42209         }
42210         function getTargetType(type) {
42211             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42212         }
42213         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42214         function hasBaseType(type, checkBase) {
42215             return check(type);
42216             function check(type) {
42217                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42218                     var target = getTargetType(type);
42219                     return target === checkBase || ts.some(getBaseTypes(target), check);
42220                 }
42221                 else if (type.flags & 2097152 /* Intersection */) {
42222                     return ts.some(type.types, check);
42223                 }
42224                 return false;
42225             }
42226         }
42227         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42228         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42229         // in-place and returns the same array.
42230         function appendTypeParameters(typeParameters, declarations) {
42231             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42232                 var declaration = declarations_2[_i];
42233                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42234             }
42235             return typeParameters;
42236         }
42237         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42238         function getOuterTypeParameters(node, includeThisTypes) {
42239             while (true) {
42240                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42241                 if (node && ts.isBinaryExpression(node)) {
42242                     // prototype assignments get the outer type parameters of their constructor function
42243                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42244                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42245                         var symbol = getSymbolOfNode(node.left);
42246                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42247                             node = symbol.parent.valueDeclaration;
42248                         }
42249                     }
42250                 }
42251                 if (!node) {
42252                     return undefined;
42253                 }
42254                 switch (node.kind) {
42255                     case 225 /* VariableStatement */:
42256                     case 245 /* ClassDeclaration */:
42257                     case 214 /* ClassExpression */:
42258                     case 246 /* InterfaceDeclaration */:
42259                     case 165 /* CallSignature */:
42260                     case 166 /* ConstructSignature */:
42261                     case 160 /* MethodSignature */:
42262                     case 170 /* FunctionType */:
42263                     case 171 /* ConstructorType */:
42264                     case 300 /* JSDocFunctionType */:
42265                     case 244 /* FunctionDeclaration */:
42266                     case 161 /* MethodDeclaration */:
42267                     case 201 /* FunctionExpression */:
42268                     case 202 /* ArrowFunction */:
42269                     case 247 /* TypeAliasDeclaration */:
42270                     case 321 /* JSDocTemplateTag */:
42271                     case 322 /* JSDocTypedefTag */:
42272                     case 316 /* JSDocEnumTag */:
42273                     case 315 /* JSDocCallbackTag */:
42274                     case 186 /* MappedType */:
42275                     case 180 /* ConditionalType */:
42276                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42277                         if (node.kind === 186 /* MappedType */) {
42278                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42279                         }
42280                         else if (node.kind === 180 /* ConditionalType */) {
42281                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42282                         }
42283                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42284                             break;
42285                         }
42286                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42287                         var thisType = includeThisTypes &&
42288                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42289                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42290                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42291                 }
42292             }
42293         }
42294         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42295         function getOuterTypeParametersOfClassOrInterface(symbol) {
42296             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42297             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42298             return getOuterTypeParameters(declaration);
42299         }
42300         // The local type parameters are the combined set of type parameters from all declarations of the class,
42301         // interface, or type alias.
42302         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42303             var result;
42304             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42305                 var node = _a[_i];
42306                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42307                     node.kind === 245 /* ClassDeclaration */ ||
42308                     node.kind === 214 /* ClassExpression */ ||
42309                     isJSConstructor(node) ||
42310                     ts.isTypeAlias(node)) {
42311                     var declaration = node;
42312                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42313                 }
42314             }
42315             return result;
42316         }
42317         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42318         // its locally declared type parameters.
42319         function getTypeParametersOfClassOrInterface(symbol) {
42320             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42321         }
42322         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42323         // rest parameter of type any[].
42324         function isMixinConstructorType(type) {
42325             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42326             if (signatures.length === 1) {
42327                 var s = signatures[0];
42328                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42329             }
42330             return false;
42331         }
42332         function isConstructorType(type) {
42333             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42334                 return true;
42335             }
42336             if (type.flags & 8650752 /* TypeVariable */) {
42337                 var constraint = getBaseConstraintOfType(type);
42338                 return !!constraint && isMixinConstructorType(constraint);
42339             }
42340             return false;
42341         }
42342         function getBaseTypeNodeOfClass(type) {
42343             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42344         }
42345         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42346             var typeArgCount = ts.length(typeArgumentNodes);
42347             var isJavascript = ts.isInJSFile(location);
42348             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42349         }
42350         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42351             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42352             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42353             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42354         }
42355         /**
42356          * The base constructor of a class can resolve to
42357          * * undefinedType if the class has no extends clause,
42358          * * unknownType if an error occurred during resolution of the extends expression,
42359          * * nullType if the extends expression is the null value,
42360          * * anyType if the extends expression has type any, or
42361          * * an object type with at least one construct signature.
42362          */
42363         function getBaseConstructorTypeOfClass(type) {
42364             if (!type.resolvedBaseConstructorType) {
42365                 var decl = type.symbol.valueDeclaration;
42366                 var extended = ts.getEffectiveBaseTypeNode(decl);
42367                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42368                 if (!baseTypeNode) {
42369                     return type.resolvedBaseConstructorType = undefinedType;
42370                 }
42371                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42372                     return errorType;
42373                 }
42374                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42375                 if (extended && baseTypeNode !== extended) {
42376                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42377                     checkExpression(extended.expression);
42378                 }
42379                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42380                     // Resolving the members of a class requires us to resolve the base class of that class.
42381                     // We force resolution here such that we catch circularities now.
42382                     resolveStructuredTypeMembers(baseConstructorType);
42383                 }
42384                 if (!popTypeResolution()) {
42385                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42386                     return type.resolvedBaseConstructorType = errorType;
42387                 }
42388                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42389                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42390                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42391                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42392                         var ctorReturn = unknownType;
42393                         if (constraint) {
42394                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42395                             if (ctorSig[0]) {
42396                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42397                             }
42398                         }
42399                         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)));
42400                     }
42401                     return type.resolvedBaseConstructorType = errorType;
42402                 }
42403                 type.resolvedBaseConstructorType = baseConstructorType;
42404             }
42405             return type.resolvedBaseConstructorType;
42406         }
42407         function getImplementsTypes(type) {
42408             var resolvedImplementsTypes = ts.emptyArray;
42409             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42410                 var declaration = _a[_i];
42411                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42412                 if (!implementsTypeNodes)
42413                     continue;
42414                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42415                     var node = implementsTypeNodes_1[_b];
42416                     var implementsType = getTypeFromTypeNode(node);
42417                     if (implementsType !== errorType) {
42418                         if (resolvedImplementsTypes === ts.emptyArray) {
42419                             resolvedImplementsTypes = [implementsType];
42420                         }
42421                         else {
42422                             resolvedImplementsTypes.push(implementsType);
42423                         }
42424                     }
42425                 }
42426             }
42427             return resolvedImplementsTypes;
42428         }
42429         function getBaseTypes(type) {
42430             if (!type.resolvedBaseTypes) {
42431                 if (type.objectFlags & 8 /* Tuple */) {
42432                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42433                 }
42434                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42435                     if (type.symbol.flags & 32 /* Class */) {
42436                         resolveBaseTypesOfClass(type);
42437                     }
42438                     if (type.symbol.flags & 64 /* Interface */) {
42439                         resolveBaseTypesOfInterface(type);
42440                     }
42441                 }
42442                 else {
42443                     ts.Debug.fail("type must be class or interface");
42444                 }
42445             }
42446             return type.resolvedBaseTypes;
42447         }
42448         function resolveBaseTypesOfClass(type) {
42449             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42450             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42451             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42452                 return type.resolvedBaseTypes = ts.emptyArray;
42453             }
42454             var baseTypeNode = getBaseTypeNodeOfClass(type);
42455             var baseType;
42456             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42457             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42458                 areAllOuterTypeParametersApplied(originalBaseType)) {
42459                 // 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
42460                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42461                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42462                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42463             }
42464             else if (baseConstructorType.flags & 1 /* Any */) {
42465                 baseType = baseConstructorType;
42466             }
42467             else {
42468                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42469                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42470                 // we check that all instantiated signatures return the same type.
42471                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42472                 if (!constructors.length) {
42473                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42474                     return type.resolvedBaseTypes = ts.emptyArray;
42475                 }
42476                 baseType = getReturnTypeOfSignature(constructors[0]);
42477             }
42478             if (baseType === errorType) {
42479                 return type.resolvedBaseTypes = ts.emptyArray;
42480             }
42481             var reducedBaseType = getReducedType(baseType);
42482             if (!isValidBaseType(reducedBaseType)) {
42483                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42484                 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));
42485                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42486                 return type.resolvedBaseTypes = ts.emptyArray;
42487             }
42488             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42489                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42490                 return type.resolvedBaseTypes = ts.emptyArray;
42491             }
42492             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42493                 // Circular reference, likely through instantiation of default parameters
42494                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42495                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42496                 // partial instantiation of the members without the base types fully resolved
42497                 type.members = undefined;
42498             }
42499             return type.resolvedBaseTypes = [reducedBaseType];
42500         }
42501         function areAllOuterTypeParametersApplied(type) {
42502             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42503             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42504             var outerTypeParameters = type.outerTypeParameters;
42505             if (outerTypeParameters) {
42506                 var last_1 = outerTypeParameters.length - 1;
42507                 var typeArguments = getTypeArguments(type);
42508                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42509             }
42510             return true;
42511         }
42512         // A valid base type is `any`, an object type or intersection of object types.
42513         function isValidBaseType(type) {
42514             if (type.flags & 262144 /* TypeParameter */) {
42515                 var constraint = getBaseConstraintOfType(type);
42516                 if (constraint) {
42517                     return isValidBaseType(constraint);
42518                 }
42519             }
42520             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42521             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42522             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42523                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42524         }
42525         function resolveBaseTypesOfInterface(type) {
42526             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42527             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42528                 var declaration = _a[_i];
42529                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42530                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42531                         var node = _c[_b];
42532                         var baseType = getReducedType(getTypeFromTypeNode(node));
42533                         if (baseType !== errorType) {
42534                             if (isValidBaseType(baseType)) {
42535                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42536                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42537                                         type.resolvedBaseTypes = [baseType];
42538                                     }
42539                                     else {
42540                                         type.resolvedBaseTypes.push(baseType);
42541                                     }
42542                                 }
42543                                 else {
42544                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42545                                 }
42546                             }
42547                             else {
42548                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42549                             }
42550                         }
42551                     }
42552                 }
42553             }
42554         }
42555         /**
42556          * Returns true if the interface given by the symbol is free of "this" references.
42557          *
42558          * Specifically, the result is true if the interface itself contains no references
42559          * to "this" in its body, if all base types are interfaces,
42560          * and if none of the base interfaces have a "this" type.
42561          */
42562         function isThislessInterface(symbol) {
42563             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42564                 var declaration = _a[_i];
42565                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42566                     if (declaration.flags & 128 /* ContainsThis */) {
42567                         return false;
42568                     }
42569                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42570                     if (baseTypeNodes) {
42571                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42572                             var node = baseTypeNodes_1[_b];
42573                             if (ts.isEntityNameExpression(node.expression)) {
42574                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42575                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42576                                     return false;
42577                                 }
42578                             }
42579                         }
42580                     }
42581                 }
42582             }
42583             return true;
42584         }
42585         function getDeclaredTypeOfClassOrInterface(symbol) {
42586             var links = getSymbolLinks(symbol);
42587             var originalLinks = links;
42588             if (!links.declaredType) {
42589                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42590                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42591                 if (merged) {
42592                     // note:we overwrite links because we just cloned the symbol
42593                     symbol = links = merged;
42594                 }
42595                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42596                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42597                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42598                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42599                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42600                 // property types inferred from initializers and method return types inferred from return statements are very hard
42601                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42602                 // "this" references.
42603                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42604                     type.objectFlags |= 4 /* Reference */;
42605                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42606                     type.outerTypeParameters = outerTypeParameters;
42607                     type.localTypeParameters = localTypeParameters;
42608                     type.instantiations = ts.createMap();
42609                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42610                     type.target = type;
42611                     type.resolvedTypeArguments = type.typeParameters;
42612                     type.thisType = createTypeParameter(symbol);
42613                     type.thisType.isThisType = true;
42614                     type.thisType.constraint = type;
42615                 }
42616             }
42617             return links.declaredType;
42618         }
42619         function getDeclaredTypeOfTypeAlias(symbol) {
42620             var links = getSymbolLinks(symbol);
42621             if (!links.declaredType) {
42622                 // Note that we use the links object as the target here because the symbol object is used as the unique
42623                 // identity for resolution of the 'type' property in SymbolLinks.
42624                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42625                     return errorType;
42626                 }
42627                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42628                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42629                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42630                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42631                 if (popTypeResolution()) {
42632                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42633                     if (typeParameters) {
42634                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42635                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42636                         links.typeParameters = typeParameters;
42637                         links.instantiations = ts.createMap();
42638                         links.instantiations.set(getTypeListId(typeParameters), type);
42639                     }
42640                 }
42641                 else {
42642                     type = errorType;
42643                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42644                 }
42645                 links.declaredType = type;
42646             }
42647             return links.declaredType;
42648         }
42649         function isStringConcatExpression(expr) {
42650             if (ts.isStringLiteralLike(expr)) {
42651                 return true;
42652             }
42653             else if (expr.kind === 209 /* BinaryExpression */) {
42654                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42655             }
42656             return false;
42657         }
42658         function isLiteralEnumMember(member) {
42659             var expr = member.initializer;
42660             if (!expr) {
42661                 return !(member.flags & 8388608 /* Ambient */);
42662             }
42663             switch (expr.kind) {
42664                 case 10 /* StringLiteral */:
42665                 case 8 /* NumericLiteral */:
42666                 case 14 /* NoSubstitutionTemplateLiteral */:
42667                     return true;
42668                 case 207 /* PrefixUnaryExpression */:
42669                     return expr.operator === 40 /* MinusToken */ &&
42670                         expr.operand.kind === 8 /* NumericLiteral */;
42671                 case 75 /* Identifier */:
42672                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42673                 case 209 /* BinaryExpression */:
42674                     return isStringConcatExpression(expr);
42675                 default:
42676                     return false;
42677             }
42678         }
42679         function getEnumKind(symbol) {
42680             var links = getSymbolLinks(symbol);
42681             if (links.enumKind !== undefined) {
42682                 return links.enumKind;
42683             }
42684             var hasNonLiteralMember = false;
42685             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42686                 var declaration = _a[_i];
42687                 if (declaration.kind === 248 /* EnumDeclaration */) {
42688                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42689                         var member = _c[_b];
42690                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42691                             return links.enumKind = 1 /* Literal */;
42692                         }
42693                         if (!isLiteralEnumMember(member)) {
42694                             hasNonLiteralMember = true;
42695                         }
42696                     }
42697                 }
42698             }
42699             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42700         }
42701         function getBaseTypeOfEnumLiteralType(type) {
42702             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42703         }
42704         function getDeclaredTypeOfEnum(symbol) {
42705             var links = getSymbolLinks(symbol);
42706             if (links.declaredType) {
42707                 return links.declaredType;
42708             }
42709             if (getEnumKind(symbol) === 1 /* Literal */) {
42710                 enumCount++;
42711                 var memberTypeList = [];
42712                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42713                     var declaration = _a[_i];
42714                     if (declaration.kind === 248 /* EnumDeclaration */) {
42715                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42716                             var member = _c[_b];
42717                             var value = getEnumMemberValue(member);
42718                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42719                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42720                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42721                         }
42722                     }
42723                 }
42724                 if (memberTypeList.length) {
42725                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42726                     if (enumType_1.flags & 1048576 /* Union */) {
42727                         enumType_1.flags |= 1024 /* EnumLiteral */;
42728                         enumType_1.symbol = symbol;
42729                     }
42730                     return links.declaredType = enumType_1;
42731                 }
42732             }
42733             var enumType = createType(32 /* Enum */);
42734             enumType.symbol = symbol;
42735             return links.declaredType = enumType;
42736         }
42737         function getDeclaredTypeOfEnumMember(symbol) {
42738             var links = getSymbolLinks(symbol);
42739             if (!links.declaredType) {
42740                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42741                 if (!links.declaredType) {
42742                     links.declaredType = enumType;
42743                 }
42744             }
42745             return links.declaredType;
42746         }
42747         function getDeclaredTypeOfTypeParameter(symbol) {
42748             var links = getSymbolLinks(symbol);
42749             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42750         }
42751         function getDeclaredTypeOfAlias(symbol) {
42752             var links = getSymbolLinks(symbol);
42753             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42754         }
42755         function getDeclaredTypeOfSymbol(symbol) {
42756             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42757         }
42758         function tryGetDeclaredTypeOfSymbol(symbol) {
42759             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42760                 return getDeclaredTypeOfClassOrInterface(symbol);
42761             }
42762             if (symbol.flags & 524288 /* TypeAlias */) {
42763                 return getDeclaredTypeOfTypeAlias(symbol);
42764             }
42765             if (symbol.flags & 262144 /* TypeParameter */) {
42766                 return getDeclaredTypeOfTypeParameter(symbol);
42767             }
42768             if (symbol.flags & 384 /* Enum */) {
42769                 return getDeclaredTypeOfEnum(symbol);
42770             }
42771             if (symbol.flags & 8 /* EnumMember */) {
42772                 return getDeclaredTypeOfEnumMember(symbol);
42773             }
42774             if (symbol.flags & 2097152 /* Alias */) {
42775                 return getDeclaredTypeOfAlias(symbol);
42776             }
42777             return undefined;
42778         }
42779         /**
42780          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42781          * literal type, an array with an element type that is free of this references, or a type reference that is
42782          * free of this references.
42783          */
42784         function isThislessType(node) {
42785             switch (node.kind) {
42786                 case 125 /* AnyKeyword */:
42787                 case 148 /* UnknownKeyword */:
42788                 case 143 /* StringKeyword */:
42789                 case 140 /* NumberKeyword */:
42790                 case 151 /* BigIntKeyword */:
42791                 case 128 /* BooleanKeyword */:
42792                 case 144 /* SymbolKeyword */:
42793                 case 141 /* ObjectKeyword */:
42794                 case 110 /* VoidKeyword */:
42795                 case 146 /* UndefinedKeyword */:
42796                 case 100 /* NullKeyword */:
42797                 case 137 /* NeverKeyword */:
42798                 case 187 /* LiteralType */:
42799                     return true;
42800                 case 174 /* ArrayType */:
42801                     return isThislessType(node.elementType);
42802                 case 169 /* TypeReference */:
42803                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42804             }
42805             return false;
42806         }
42807         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42808         function isThislessTypeParameter(node) {
42809             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42810             return !constraint || isThislessType(constraint);
42811         }
42812         /**
42813          * A variable-like declaration is free of this references if it has a type annotation
42814          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42815          */
42816         function isThislessVariableLikeDeclaration(node) {
42817             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42818             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42819         }
42820         /**
42821          * A function-like declaration is considered free of `this` references if it has a return type
42822          * annotation that is free of this references and if each parameter is thisless and if
42823          * each type parameter (if present) is thisless.
42824          */
42825         function isThislessFunctionLikeDeclaration(node) {
42826             var returnType = ts.getEffectiveReturnTypeNode(node);
42827             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
42828             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
42829                 node.parameters.every(isThislessVariableLikeDeclaration) &&
42830                 typeParameters.every(isThislessTypeParameter);
42831         }
42832         /**
42833          * Returns true if the class or interface member given by the symbol is free of "this" references. The
42834          * function may return false for symbols that are actually free of "this" references because it is not
42835          * feasible to perform a complete analysis in all cases. In particular, property members with types
42836          * inferred from their initializers and function members with inferred return types are conservatively
42837          * assumed not to be free of "this" references.
42838          */
42839         function isThisless(symbol) {
42840             if (symbol.declarations && symbol.declarations.length === 1) {
42841                 var declaration = symbol.declarations[0];
42842                 if (declaration) {
42843                     switch (declaration.kind) {
42844                         case 159 /* PropertyDeclaration */:
42845                         case 158 /* PropertySignature */:
42846                             return isThislessVariableLikeDeclaration(declaration);
42847                         case 161 /* MethodDeclaration */:
42848                         case 160 /* MethodSignature */:
42849                         case 162 /* Constructor */:
42850                         case 163 /* GetAccessor */:
42851                         case 164 /* SetAccessor */:
42852                             return isThislessFunctionLikeDeclaration(declaration);
42853                     }
42854                 }
42855             }
42856             return false;
42857         }
42858         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
42859         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
42860         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
42861             var result = ts.createSymbolTable();
42862             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
42863                 var symbol = symbols_2[_i];
42864                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
42865             }
42866             return result;
42867         }
42868         function addInheritedMembers(symbols, baseSymbols) {
42869             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
42870                 var s = baseSymbols_1[_i];
42871                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
42872                     symbols.set(s.escapedName, s);
42873                 }
42874             }
42875         }
42876         function isStaticPrivateIdentifierProperty(s) {
42877             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
42878         }
42879         function resolveDeclaredMembers(type) {
42880             if (!type.declaredProperties) {
42881                 var symbol = type.symbol;
42882                 var members = getMembersOfSymbol(symbol);
42883                 type.declaredProperties = getNamedMembers(members);
42884                 // Start with signatures at empty array in case of recursive types
42885                 type.declaredCallSignatures = ts.emptyArray;
42886                 type.declaredConstructSignatures = ts.emptyArray;
42887                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
42888                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
42889                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
42890                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
42891             }
42892             return type;
42893         }
42894         /**
42895          * Indicates whether a type can be used as a property name.
42896          */
42897         function isTypeUsableAsPropertyName(type) {
42898             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
42899         }
42900         /**
42901          * Indicates whether a declaration name is definitely late-bindable.
42902          * A declaration name is only late-bindable if:
42903          * - It is a `ComputedPropertyName`.
42904          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
42905          * `ElementAccessExpression` consisting only of these same three types of nodes.
42906          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
42907          */
42908         function isLateBindableName(node) {
42909             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
42910                 return false;
42911             }
42912             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
42913             return ts.isEntityNameExpression(expr)
42914                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
42915         }
42916         function isLateBoundName(name) {
42917             return name.charCodeAt(0) === 95 /* _ */ &&
42918                 name.charCodeAt(1) === 95 /* _ */ &&
42919                 name.charCodeAt(2) === 64 /* at */;
42920         }
42921         /**
42922          * Indicates whether a declaration has a late-bindable dynamic name.
42923          */
42924         function hasLateBindableName(node) {
42925             var name = ts.getNameOfDeclaration(node);
42926             return !!name && isLateBindableName(name);
42927         }
42928         /**
42929          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
42930          */
42931         function hasNonBindableDynamicName(node) {
42932             return ts.hasDynamicName(node) && !hasLateBindableName(node);
42933         }
42934         /**
42935          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
42936          */
42937         function isNonBindableDynamicName(node) {
42938             return ts.isDynamicName(node) && !isLateBindableName(node);
42939         }
42940         /**
42941          * Gets the symbolic name for a member from its type.
42942          */
42943         function getPropertyNameFromType(type) {
42944             if (type.flags & 8192 /* UniqueESSymbol */) {
42945                 return type.escapedName;
42946             }
42947             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
42948                 return ts.escapeLeadingUnderscores("" + type.value);
42949             }
42950             return ts.Debug.fail();
42951         }
42952         /**
42953          * Adds a declaration to a late-bound dynamic member. This performs the same function for
42954          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
42955          * members.
42956          */
42957         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
42958             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
42959             symbol.flags |= symbolFlags;
42960             getSymbolLinks(member.symbol).lateSymbol = symbol;
42961             if (!symbol.declarations) {
42962                 symbol.declarations = [member];
42963             }
42964             else {
42965                 symbol.declarations.push(member);
42966             }
42967             if (symbolFlags & 111551 /* Value */) {
42968                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
42969                     symbol.valueDeclaration = member;
42970                 }
42971             }
42972         }
42973         /**
42974          * Performs late-binding of a dynamic member. This performs the same function for
42975          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
42976          * members.
42977          *
42978          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
42979          * binding phase to attempt to resolve the name for the symbol from the type of the computed
42980          * property's expression. If the type of the expression is a string-literal, numeric-literal,
42981          * or unique symbol type, we can use that type as the name of the symbol.
42982          *
42983          * For example, given:
42984          *
42985          *   const x = Symbol();
42986          *
42987          *   interface I {
42988          *     [x]: number;
42989          *   }
42990          *
42991          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
42992          * In the late-binding phase we can type-check the expression `x` and see that it has a
42993          * unique symbol type which we can then use as the name of the member. This allows users
42994          * to define custom symbols that can be used in the members of an object type.
42995          *
42996          * @param parent The containing symbol for the member.
42997          * @param earlySymbols The early-bound symbols of the parent.
42998          * @param lateSymbols The late-bound symbols of the parent.
42999          * @param decl The member to bind.
43000          */
43001         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43002             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43003             var links = getNodeLinks(decl);
43004             if (!links.resolvedSymbol) {
43005                 // In the event we attempt to resolve the late-bound name of this member recursively,
43006                 // fall back to the early-bound name of this member.
43007                 links.resolvedSymbol = decl.symbol;
43008                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43009                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43010                 if (isTypeUsableAsPropertyName(type)) {
43011                     var memberName = getPropertyNameFromType(type);
43012                     var symbolFlags = decl.symbol.flags;
43013                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43014                     var lateSymbol = lateSymbols.get(memberName);
43015                     if (!lateSymbol)
43016                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43017                     // Report an error if a late-bound member has the same name as an early-bound member,
43018                     // or if we have another early-bound symbol declaration with the same name and
43019                     // conflicting flags.
43020                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43021                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43022                         // If we have an existing early-bound member, combine its declarations so that we can
43023                         // report an error at each declaration.
43024                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43025                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43026                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43027                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43028                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43029                     }
43030                     lateSymbol.nameType = type;
43031                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43032                     if (lateSymbol.parent) {
43033                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43034                     }
43035                     else {
43036                         lateSymbol.parent = parent;
43037                     }
43038                     return links.resolvedSymbol = lateSymbol;
43039                 }
43040             }
43041             return links.resolvedSymbol;
43042         }
43043         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43044             var links = getSymbolLinks(symbol);
43045             if (!links[resolutionKind]) {
43046                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43047                 var earlySymbols = !isStatic ? symbol.members :
43048                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43049                         symbol.exports;
43050                 // In the event we recursively resolve the members/exports of the symbol, we
43051                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43052                 // members/exports of the symbol.
43053                 links[resolutionKind] = earlySymbols || emptySymbols;
43054                 // fill in any as-yet-unresolved late-bound members.
43055                 var lateSymbols = ts.createSymbolTable();
43056                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43057                     var decl = _a[_i];
43058                     var members = ts.getMembersOfDeclaration(decl);
43059                     if (members) {
43060                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43061                             var member = members_5[_b];
43062                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43063                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43064                             }
43065                         }
43066                     }
43067                 }
43068                 var assignments = symbol.assignmentDeclarationMembers;
43069                 if (assignments) {
43070                     var decls = ts.arrayFrom(assignments.values());
43071                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43072                         var member = decls_1[_c];
43073                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43074                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43075                             || assignmentKind === 4 /* ThisProperty */
43076                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43077                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43078                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43079                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43080                         }
43081                     }
43082                 }
43083                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43084             }
43085             return links[resolutionKind];
43086         }
43087         /**
43088          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43089          *
43090          * For a description of late-binding, see `lateBindMember`.
43091          */
43092         function getMembersOfSymbol(symbol) {
43093             return symbol.flags & 6256 /* LateBindingContainer */
43094                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43095                 : symbol.members || emptySymbols;
43096         }
43097         /**
43098          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43099          * symbol of the member.
43100          *
43101          * For a description of late-binding, see `lateBindMember`.
43102          */
43103         function getLateBoundSymbol(symbol) {
43104             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43105                 var links = getSymbolLinks(symbol);
43106                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43107                     // force late binding of members/exports. This will set the late-bound symbol
43108                     var parent = getMergedSymbol(symbol.parent);
43109                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43110                         getExportsOfSymbol(parent);
43111                     }
43112                     else {
43113                         getMembersOfSymbol(parent);
43114                     }
43115                 }
43116                 return links.lateSymbol || (links.lateSymbol = symbol);
43117             }
43118             return symbol;
43119         }
43120         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43121             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43122                 var target = type.target;
43123                 var typeArguments = getTypeArguments(type);
43124                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43125                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43126                     return needApparentType ? getApparentType(ref) : ref;
43127                 }
43128             }
43129             else if (type.flags & 2097152 /* Intersection */) {
43130                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43131             }
43132             return needApparentType ? getApparentType(type) : type;
43133         }
43134         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43135             var mapper;
43136             var members;
43137             var callSignatures;
43138             var constructSignatures;
43139             var stringIndexInfo;
43140             var numberIndexInfo;
43141             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43142                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43143                 callSignatures = source.declaredCallSignatures;
43144                 constructSignatures = source.declaredConstructSignatures;
43145                 stringIndexInfo = source.declaredStringIndexInfo;
43146                 numberIndexInfo = source.declaredNumberIndexInfo;
43147             }
43148             else {
43149                 mapper = createTypeMapper(typeParameters, typeArguments);
43150                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43151                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43152                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43153                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43154                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43155             }
43156             var baseTypes = getBaseTypes(source);
43157             if (baseTypes.length) {
43158                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43159                     members = ts.createSymbolTable(source.declaredProperties);
43160                 }
43161                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43162                 var thisArgument = ts.lastOrUndefined(typeArguments);
43163                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43164                     var baseType = baseTypes_1[_i];
43165                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43166                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43167                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43168                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43169                     if (!stringIndexInfo) {
43170                         stringIndexInfo = instantiatedBaseType === anyType ?
43171                             createIndexInfo(anyType, /*isReadonly*/ false) :
43172                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43173                     }
43174                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43175                 }
43176             }
43177             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43178         }
43179         function resolveClassOrInterfaceMembers(type) {
43180             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43181         }
43182         function resolveTypeReferenceMembers(type) {
43183             var source = resolveDeclaredMembers(type.target);
43184             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43185             var typeArguments = getTypeArguments(type);
43186             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43187             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43188         }
43189         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43190             var sig = new Signature(checker, flags);
43191             sig.declaration = declaration;
43192             sig.typeParameters = typeParameters;
43193             sig.parameters = parameters;
43194             sig.thisParameter = thisParameter;
43195             sig.resolvedReturnType = resolvedReturnType;
43196             sig.resolvedTypePredicate = resolvedTypePredicate;
43197             sig.minArgumentCount = minArgumentCount;
43198             sig.target = undefined;
43199             sig.mapper = undefined;
43200             sig.unionSignatures = undefined;
43201             return sig;
43202         }
43203         function cloneSignature(sig) {
43204             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43205             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43206             result.target = sig.target;
43207             result.mapper = sig.mapper;
43208             result.unionSignatures = sig.unionSignatures;
43209             return result;
43210         }
43211         function createUnionSignature(signature, unionSignatures) {
43212             var result = cloneSignature(signature);
43213             result.unionSignatures = unionSignatures;
43214             result.target = undefined;
43215             result.mapper = undefined;
43216             return result;
43217         }
43218         function getOptionalCallSignature(signature, callChainFlags) {
43219             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43220                 return signature;
43221             }
43222             if (!signature.optionalCallSignatureCache) {
43223                 signature.optionalCallSignatureCache = {};
43224             }
43225             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43226             return signature.optionalCallSignatureCache[key]
43227                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43228         }
43229         function createOptionalCallSignature(signature, callChainFlags) {
43230             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.");
43231             var result = cloneSignature(signature);
43232             result.flags |= callChainFlags;
43233             return result;
43234         }
43235         function getExpandedParameters(sig) {
43236             if (signatureHasRestParameter(sig)) {
43237                 var restIndex_1 = sig.parameters.length - 1;
43238                 var restParameter = sig.parameters[restIndex_1];
43239                 var restType = getTypeOfSymbol(restParameter);
43240                 if (isTupleType(restType)) {
43241                     var elementTypes = getTypeArguments(restType);
43242                     var minLength_1 = restType.target.minLength;
43243                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43244                     var restParams = ts.map(elementTypes, function (t, i) {
43245                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43246                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43247                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43248                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43249                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43250                         return symbol;
43251                     });
43252                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43253                 }
43254             }
43255             return sig.parameters;
43256         }
43257         function getDefaultConstructSignatures(classType) {
43258             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43259             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43260             if (baseSignatures.length === 0) {
43261                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43262             }
43263             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43264             var isJavaScript = ts.isInJSFile(baseTypeNode);
43265             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43266             var typeArgCount = ts.length(typeArguments);
43267             var result = [];
43268             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43269                 var baseSig = baseSignatures_1[_i];
43270                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43271                 var typeParamCount = ts.length(baseSig.typeParameters);
43272                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43273                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43274                     sig.typeParameters = classType.localTypeParameters;
43275                     sig.resolvedReturnType = classType;
43276                     result.push(sig);
43277                 }
43278             }
43279             return result;
43280         }
43281         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43282             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43283                 var s = signatureList_1[_i];
43284                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43285                     return s;
43286                 }
43287             }
43288         }
43289         function findMatchingSignatures(signatureLists, signature, listIndex) {
43290             if (signature.typeParameters) {
43291                 // We require an exact match for generic signatures, so we only return signatures from the first
43292                 // signature list and only if they have exact matches in the other signature lists.
43293                 if (listIndex > 0) {
43294                     return undefined;
43295                 }
43296                 for (var i = 1; i < signatureLists.length; i++) {
43297                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43298                         return undefined;
43299                     }
43300                 }
43301                 return [signature];
43302             }
43303             var result;
43304             for (var i = 0; i < signatureLists.length; i++) {
43305                 // Allow matching non-generic signatures to have excess parameters and different return types.
43306                 // Prefer matching this types if possible.
43307                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43308                 if (!match) {
43309                     return undefined;
43310                 }
43311                 result = ts.appendIfUnique(result, match);
43312             }
43313             return result;
43314         }
43315         // The signatures of a union type are those signatures that are present in each of the constituent types.
43316         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43317         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43318         // type is the union of the constituent return types.
43319         function getUnionSignatures(signatureLists) {
43320             var result;
43321             var indexWithLengthOverOne;
43322             for (var i = 0; i < signatureLists.length; i++) {
43323                 if (signatureLists[i].length === 0)
43324                     return ts.emptyArray;
43325                 if (signatureLists[i].length > 1) {
43326                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43327                 }
43328                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43329                     var signature = _a[_i];
43330                     // Only process signatures with parameter lists that aren't already in the result list
43331                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43332                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43333                         if (unionSignatures) {
43334                             var s = signature;
43335                             // Union the result types when more than one signature matches
43336                             if (unionSignatures.length > 1) {
43337                                 var thisParameter = signature.thisParameter;
43338                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43339                                 if (firstThisParameterOfUnionSignatures) {
43340                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43341                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43342                                 }
43343                                 s = createUnionSignature(signature, unionSignatures);
43344                                 s.thisParameter = thisParameter;
43345                             }
43346                             (result || (result = [])).push(s);
43347                         }
43348                     }
43349                 }
43350             }
43351             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43352                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43353                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43354                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43355                 // signatures from the type, whose ordering would be non-obvious)
43356                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43357                 var results = masterList.slice();
43358                 var _loop_9 = function (signatures) {
43359                     if (signatures !== masterList) {
43360                         var signature_1 = signatures[0];
43361                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43362                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43363                         if (!results) {
43364                             return "break";
43365                         }
43366                     }
43367                 };
43368                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43369                     var signatures = signatureLists_1[_b];
43370                     var state_3 = _loop_9(signatures);
43371                     if (state_3 === "break")
43372                         break;
43373                 }
43374                 result = results;
43375             }
43376             return result || ts.emptyArray;
43377         }
43378         function combineUnionThisParam(left, right) {
43379             if (!left || !right) {
43380                 return left || right;
43381             }
43382             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43383             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43384             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43385             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43386             return createSymbolWithType(left, thisType);
43387         }
43388         function combineUnionParameters(left, right) {
43389             var leftCount = getParameterCount(left);
43390             var rightCount = getParameterCount(right);
43391             var longest = leftCount >= rightCount ? left : right;
43392             var shorter = longest === left ? right : left;
43393             var longestCount = longest === left ? leftCount : rightCount;
43394             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43395             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43396             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43397             for (var i = 0; i < longestCount; i++) {
43398                 var longestParamType = tryGetTypeAtPosition(longest, i);
43399                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43400                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43401                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43402                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43403                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43404                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43405                 var paramName = leftName === rightName ? leftName :
43406                     !leftName ? rightName :
43407                         !rightName ? leftName :
43408                             undefined;
43409                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43410                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43411                 params[i] = paramSymbol;
43412             }
43413             if (needsExtraRestElement) {
43414                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43415                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43416                 params[longestCount] = restParamSymbol;
43417             }
43418             return params;
43419         }
43420         function combineSignaturesOfUnionMembers(left, right) {
43421             var declaration = left.declaration;
43422             var params = combineUnionParameters(left, right);
43423             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43424             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43425             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43426             /*resolvedReturnType*/ undefined, 
43427             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43428             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43429             return result;
43430         }
43431         function getUnionIndexInfo(types, kind) {
43432             var indexTypes = [];
43433             var isAnyReadonly = false;
43434             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43435                 var type = types_3[_i];
43436                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43437                 if (!indexInfo) {
43438                     return undefined;
43439                 }
43440                 indexTypes.push(indexInfo.type);
43441                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43442             }
43443             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43444         }
43445         function resolveUnionTypeMembers(type) {
43446             // The members and properties collections are empty for union types. To get all properties of a union
43447             // type use getPropertiesOfType (only the language service uses this).
43448             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43449             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43450             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43451             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43452             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43453         }
43454         function intersectTypes(type1, type2) {
43455             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43456         }
43457         function intersectIndexInfos(info1, info2) {
43458             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43459         }
43460         function unionSpreadIndexInfos(info1, info2) {
43461             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43462         }
43463         function findMixins(types) {
43464             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43465             var mixinFlags = ts.map(types, isMixinConstructorType);
43466             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43467                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43468                 mixinFlags[firstMixinIndex] = false;
43469             }
43470             return mixinFlags;
43471         }
43472         function includeMixinType(type, types, mixinFlags, index) {
43473             var mixedTypes = [];
43474             for (var i = 0; i < types.length; i++) {
43475                 if (i === index) {
43476                     mixedTypes.push(type);
43477                 }
43478                 else if (mixinFlags[i]) {
43479                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43480                 }
43481             }
43482             return getIntersectionType(mixedTypes);
43483         }
43484         function resolveIntersectionTypeMembers(type) {
43485             // The members and properties collections are empty for intersection types. To get all properties of an
43486             // intersection type use getPropertiesOfType (only the language service uses this).
43487             var callSignatures;
43488             var constructSignatures;
43489             var stringIndexInfo;
43490             var numberIndexInfo;
43491             var types = type.types;
43492             var mixinFlags = findMixins(types);
43493             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43494             var _loop_10 = function (i) {
43495                 var t = type.types[i];
43496                 // When an intersection type contains mixin constructor types, the construct signatures from
43497                 // those types are discarded and their return types are mixed into the return types of all
43498                 // other construct signatures in the intersection type. For example, the intersection type
43499                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43500                 // 'new(s: string) => A & B'.
43501                 if (!mixinFlags[i]) {
43502                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43503                     if (signatures.length && mixinCount > 0) {
43504                         signatures = ts.map(signatures, function (s) {
43505                             var clone = cloneSignature(s);
43506                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43507                             return clone;
43508                         });
43509                     }
43510                     constructSignatures = appendSignatures(constructSignatures, signatures);
43511                 }
43512                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43513                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43514                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43515             };
43516             for (var i = 0; i < types.length; i++) {
43517                 _loop_10(i);
43518             }
43519             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43520         }
43521         function appendSignatures(signatures, newSignatures) {
43522             var _loop_11 = function (sig) {
43523                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43524                     signatures = ts.append(signatures, sig);
43525                 }
43526             };
43527             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43528                 var sig = newSignatures_1[_i];
43529                 _loop_11(sig);
43530             }
43531             return signatures;
43532         }
43533         /**
43534          * Converts an AnonymousType to a ResolvedType.
43535          */
43536         function resolveAnonymousTypeMembers(type) {
43537             var symbol = getMergedSymbol(type.symbol);
43538             if (type.target) {
43539                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43540                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43541                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43542                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43543                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43544                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43545                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43546             }
43547             else if (symbol.flags & 2048 /* TypeLiteral */) {
43548                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43549                 var members = getMembersOfSymbol(symbol);
43550                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43551                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43552                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43553                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43554                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43555             }
43556             else {
43557                 // Combinations of function, class, enum and module
43558                 var members = emptySymbols;
43559                 var stringIndexInfo = void 0;
43560                 if (symbol.exports) {
43561                     members = getExportsOfSymbol(symbol);
43562                     if (symbol === globalThisSymbol) {
43563                         var varsOnly_1 = ts.createMap();
43564                         members.forEach(function (p) {
43565                             if (!(p.flags & 418 /* BlockScoped */)) {
43566                                 varsOnly_1.set(p.escapedName, p);
43567                             }
43568                         });
43569                         members = varsOnly_1;
43570                     }
43571                 }
43572                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43573                 if (symbol.flags & 32 /* Class */) {
43574                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43575                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43576                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43577                         members = ts.createSymbolTable(getNamedMembers(members));
43578                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43579                     }
43580                     else if (baseConstructorType === anyType) {
43581                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43582                     }
43583                 }
43584                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43585                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43586                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43587                 // We resolve the members before computing the signatures because a signature may use
43588                 // typeof with a qualified name expression that circularly references the type we are
43589                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43590                 // will never be observed because a qualified name can't reference signatures.
43591                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43592                     type.callSignatures = getSignaturesOfSymbol(symbol);
43593                 }
43594                 // And likewise for construct signatures for classes
43595                 if (symbol.flags & 32 /* Class */) {
43596                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43597                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43598                     if (symbol.flags & 16 /* Function */) {
43599                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43600                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43601                             undefined; }));
43602                     }
43603                     if (!constructSignatures.length) {
43604                         constructSignatures = getDefaultConstructSignatures(classType_1);
43605                     }
43606                     type.constructSignatures = constructSignatures;
43607                 }
43608             }
43609         }
43610         function resolveReverseMappedTypeMembers(type) {
43611             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43612             var modifiers = getMappedTypeModifiers(type.mappedType);
43613             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43614             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43615             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43616             var members = ts.createSymbolTable();
43617             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43618                 var prop = _a[_i];
43619                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43620                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43621                 inferredProp.declarations = prop.declarations;
43622                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43623                 inferredProp.propertyType = getTypeOfSymbol(prop);
43624                 inferredProp.mappedType = type.mappedType;
43625                 inferredProp.constraintType = type.constraintType;
43626                 members.set(prop.escapedName, inferredProp);
43627             }
43628             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43629         }
43630         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43631         // bound includes those keys that are known to always be present, for example because
43632         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43633         function getLowerBoundOfKeyType(type) {
43634             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43635                 return type;
43636             }
43637             if (type.flags & 4194304 /* Index */) {
43638                 return getIndexType(getApparentType(type.type));
43639             }
43640             if (type.flags & 16777216 /* Conditional */) {
43641                 if (type.root.isDistributive) {
43642                     var checkType = type.checkType;
43643                     var constraint = getLowerBoundOfKeyType(checkType);
43644                     if (constraint !== checkType) {
43645                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43646                     }
43647                 }
43648                 return type;
43649             }
43650             if (type.flags & 1048576 /* Union */) {
43651                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43652             }
43653             if (type.flags & 2097152 /* Intersection */) {
43654                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43655             }
43656             return neverType;
43657         }
43658         /** Resolve the members of a mapped type { [P in K]: T } */
43659         function resolveMappedTypeMembers(type) {
43660             var members = ts.createSymbolTable();
43661             var stringIndexInfo;
43662             var numberIndexInfo;
43663             // Resolve upfront such that recursive references see an empty object type.
43664             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43665             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43666             // and T as the template type.
43667             var typeParameter = getTypeParameterFromMappedType(type);
43668             var constraintType = getConstraintTypeFromMappedType(type);
43669             var templateType = getTemplateTypeFromMappedType(type.target || type);
43670             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43671             var templateModifiers = getMappedTypeModifiers(type);
43672             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43673             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43674                 // We have a { [P in keyof T]: X }
43675                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43676                     var prop = _a[_i];
43677                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43678                 }
43679                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43680                     addMemberForKeyType(stringType);
43681                 }
43682                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43683                     addMemberForKeyType(numberType);
43684                 }
43685             }
43686             else {
43687                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43688             }
43689             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43690             function addMemberForKeyType(t) {
43691                 // Create a mapper from T to the current iteration type constituent. Then, if the
43692                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43693                 // instantiation mapper.
43694                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43695                 // If the current iteration type constituent is a string literal type, create a property.
43696                 // Otherwise, for type string create a string index signature.
43697                 if (isTypeUsableAsPropertyName(t)) {
43698                     var propName = getPropertyNameFromType(t);
43699                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43700                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43701                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43702                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43703                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43704                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43705                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43706                     prop.mappedType = type;
43707                     prop.mapper = templateMapper;
43708                     if (modifiersProp) {
43709                         prop.syntheticOrigin = modifiersProp;
43710                         prop.declarations = modifiersProp.declarations;
43711                     }
43712                     prop.nameType = t;
43713                     members.set(propName, prop);
43714                 }
43715                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43716                     var propType = instantiateType(templateType, templateMapper);
43717                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43718                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43719                     }
43720                     else {
43721                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43722                     }
43723                 }
43724             }
43725         }
43726         function getTypeOfMappedSymbol(symbol) {
43727             if (!symbol.type) {
43728                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43729                     return errorType;
43730                 }
43731                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43732                 var propType = instantiateType(templateType, symbol.mapper);
43733                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43734                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43735                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43736                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43737                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43738                         propType;
43739                 if (!popTypeResolution()) {
43740                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43741                     type = errorType;
43742                 }
43743                 symbol.type = type;
43744                 symbol.mapper = undefined;
43745             }
43746             return symbol.type;
43747         }
43748         function getTypeParameterFromMappedType(type) {
43749             return type.typeParameter ||
43750                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43751         }
43752         function getConstraintTypeFromMappedType(type) {
43753             return type.constraintType ||
43754                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43755         }
43756         function getTemplateTypeFromMappedType(type) {
43757             return type.templateType ||
43758                 (type.templateType = type.declaration.type ?
43759                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43760                     errorType);
43761         }
43762         function getConstraintDeclarationForMappedType(type) {
43763             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43764         }
43765         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43766             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43767             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43768                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43769         }
43770         function getModifiersTypeFromMappedType(type) {
43771             if (!type.modifiersType) {
43772                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43773                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43774                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43775                     // 'keyof T' to a literal union type and we can't recover T from that type.
43776                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43777                 }
43778                 else {
43779                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43780                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43781                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43782                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43783                     var constraint = getConstraintTypeFromMappedType(declaredType);
43784                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43785                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43786                 }
43787             }
43788             return type.modifiersType;
43789         }
43790         function getMappedTypeModifiers(type) {
43791             var declaration = type.declaration;
43792             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43793                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43794         }
43795         function getMappedTypeOptionality(type) {
43796             var modifiers = getMappedTypeModifiers(type);
43797             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43798         }
43799         function getCombinedMappedTypeOptionality(type) {
43800             var optionality = getMappedTypeOptionality(type);
43801             var modifiersType = getModifiersTypeFromMappedType(type);
43802             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43803         }
43804         function isPartialMappedType(type) {
43805             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43806         }
43807         function isGenericMappedType(type) {
43808             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43809         }
43810         function resolveStructuredTypeMembers(type) {
43811             if (!type.members) {
43812                 if (type.flags & 524288 /* Object */) {
43813                     if (type.objectFlags & 4 /* Reference */) {
43814                         resolveTypeReferenceMembers(type);
43815                     }
43816                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43817                         resolveClassOrInterfaceMembers(type);
43818                     }
43819                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43820                         resolveReverseMappedTypeMembers(type);
43821                     }
43822                     else if (type.objectFlags & 16 /* Anonymous */) {
43823                         resolveAnonymousTypeMembers(type);
43824                     }
43825                     else if (type.objectFlags & 32 /* Mapped */) {
43826                         resolveMappedTypeMembers(type);
43827                     }
43828                 }
43829                 else if (type.flags & 1048576 /* Union */) {
43830                     resolveUnionTypeMembers(type);
43831                 }
43832                 else if (type.flags & 2097152 /* Intersection */) {
43833                     resolveIntersectionTypeMembers(type);
43834                 }
43835             }
43836             return type;
43837         }
43838         /** Return properties of an object type or an empty array for other types */
43839         function getPropertiesOfObjectType(type) {
43840             if (type.flags & 524288 /* Object */) {
43841                 return resolveStructuredTypeMembers(type).properties;
43842             }
43843             return ts.emptyArray;
43844         }
43845         /** If the given type is an object type and that type has a property by the given name,
43846          * return the symbol for that property. Otherwise return undefined.
43847          */
43848         function getPropertyOfObjectType(type, name) {
43849             if (type.flags & 524288 /* Object */) {
43850                 var resolved = resolveStructuredTypeMembers(type);
43851                 var symbol = resolved.members.get(name);
43852                 if (symbol && symbolIsValue(symbol)) {
43853                     return symbol;
43854                 }
43855             }
43856         }
43857         function getPropertiesOfUnionOrIntersectionType(type) {
43858             if (!type.resolvedProperties) {
43859                 var members = ts.createSymbolTable();
43860                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
43861                     var current = _a[_i];
43862                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
43863                         var prop = _c[_b];
43864                         if (!members.has(prop.escapedName)) {
43865                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
43866                             if (combinedProp) {
43867                                 members.set(prop.escapedName, combinedProp);
43868                             }
43869                         }
43870                     }
43871                     // The properties of a union type are those that are present in all constituent types, so
43872                     // we only need to check the properties of the first type without index signature
43873                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
43874                         break;
43875                     }
43876                 }
43877                 type.resolvedProperties = getNamedMembers(members);
43878             }
43879             return type.resolvedProperties;
43880         }
43881         function getPropertiesOfType(type) {
43882             type = getReducedApparentType(type);
43883             return type.flags & 3145728 /* UnionOrIntersection */ ?
43884                 getPropertiesOfUnionOrIntersectionType(type) :
43885                 getPropertiesOfObjectType(type);
43886         }
43887         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
43888             var list = obj.properties;
43889             return list.some(function (property) {
43890                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
43891                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
43892                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
43893                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
43894             });
43895         }
43896         function getAllPossiblePropertiesOfTypes(types) {
43897             var unionType = getUnionType(types);
43898             if (!(unionType.flags & 1048576 /* Union */)) {
43899                 return getAugmentedPropertiesOfType(unionType);
43900             }
43901             var props = ts.createSymbolTable();
43902             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
43903                 var memberType = types_4[_i];
43904                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
43905                     var escapedName = _b[_a].escapedName;
43906                     if (!props.has(escapedName)) {
43907                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
43908                         // May be undefined if the property is private
43909                         if (prop)
43910                             props.set(escapedName, prop);
43911                     }
43912                 }
43913             }
43914             return ts.arrayFrom(props.values());
43915         }
43916         function getConstraintOfType(type) {
43917             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
43918                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
43919                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
43920                         getBaseConstraintOfType(type);
43921         }
43922         function getConstraintOfTypeParameter(typeParameter) {
43923             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
43924         }
43925         function getConstraintOfIndexedAccess(type) {
43926             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
43927         }
43928         function getSimplifiedTypeOrConstraint(type) {
43929             var simplified = getSimplifiedType(type, /*writing*/ false);
43930             return simplified !== type ? simplified : getConstraintOfType(type);
43931         }
43932         function getConstraintFromIndexedAccess(type) {
43933             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
43934             if (indexConstraint && indexConstraint !== type.indexType) {
43935                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
43936                 if (indexedAccess) {
43937                     return indexedAccess;
43938                 }
43939             }
43940             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
43941             if (objectConstraint && objectConstraint !== type.objectType) {
43942                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
43943             }
43944             return undefined;
43945         }
43946         function getDefaultConstraintOfConditionalType(type) {
43947             if (!type.resolvedDefaultConstraint) {
43948                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
43949                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
43950                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
43951                 // in effect treating `any` like `never` rather than `unknown` in this location.
43952                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
43953                 var falseConstraint = getFalseTypeFromConditionalType(type);
43954                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
43955             }
43956             return type.resolvedDefaultConstraint;
43957         }
43958         function getConstraintOfDistributiveConditionalType(type) {
43959             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
43960             // type parameter. If so, create an instantiation of the conditional type where T is replaced
43961             // with its constraint. We do this because if the constraint is a union type it will be distributed
43962             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
43963             // removes 'undefined' from T.
43964             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
43965             // as the constraint for all type params (check type included) have been replace with `unknown`, which
43966             // is going to produce even more false positive/negative results than the distribute constraint already does.
43967             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
43968             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
43969             // likely doesn't need to exist.
43970             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
43971                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
43972                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
43973                 if (constraint && constraint !== type.checkType) {
43974                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43975                     if (!(instantiated.flags & 131072 /* Never */)) {
43976                         return instantiated;
43977                     }
43978                 }
43979             }
43980             return undefined;
43981         }
43982         function getConstraintFromConditionalType(type) {
43983             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
43984         }
43985         function getConstraintOfConditionalType(type) {
43986             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
43987         }
43988         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
43989             var constraints;
43990             var hasDisjointDomainType = false;
43991             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
43992                 var t = types_5[_i];
43993                 if (t.flags & 63176704 /* Instantiable */) {
43994                     // We keep following constraints as long as we have an instantiable type that is known
43995                     // not to be circular or infinite (hence we stop on index access types).
43996                     var constraint = getConstraintOfType(t);
43997                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
43998                         constraint = getConstraintOfType(constraint);
43999                     }
44000                     if (constraint) {
44001                         constraints = ts.append(constraints, constraint);
44002                         if (targetIsUnion) {
44003                             constraints = ts.append(constraints, t);
44004                         }
44005                     }
44006                 }
44007                 else if (t.flags & 67238908 /* DisjointDomains */) {
44008                     hasDisjointDomainType = true;
44009                 }
44010             }
44011             // If the target is a union type or if we are intersecting with types belonging to one of the
44012             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44013             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44014                 if (hasDisjointDomainType) {
44015                     // We add any types belong to one of the disjoint domains because they might cause the final
44016                     // intersection operation to reduce the union constraints.
44017                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44018                         var t = types_6[_a];
44019                         if (t.flags & 67238908 /* DisjointDomains */) {
44020                             constraints = ts.append(constraints, t);
44021                         }
44022                     }
44023                 }
44024                 return getIntersectionType(constraints);
44025             }
44026             return undefined;
44027         }
44028         function getBaseConstraintOfType(type) {
44029             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44030                 var constraint = getResolvedBaseConstraint(type);
44031                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44032             }
44033             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44034         }
44035         /**
44036          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44037          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44038          */
44039         function getBaseConstraintOrType(type) {
44040             return getBaseConstraintOfType(type) || type;
44041         }
44042         function hasNonCircularBaseConstraint(type) {
44043             return getResolvedBaseConstraint(type) !== circularConstraintType;
44044         }
44045         /**
44046          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44047          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44048          * circularly references the type variable.
44049          */
44050         function getResolvedBaseConstraint(type) {
44051             var nonTerminating = false;
44052             return type.resolvedBaseConstraint ||
44053                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44054             function getImmediateBaseConstraint(t) {
44055                 if (!t.immediateBaseConstraint) {
44056                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44057                         return circularConstraintType;
44058                     }
44059                     if (constraintDepth >= 50) {
44060                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44061                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44062                         // new type identities as we descend into it. We stop the recursion here and mark this type
44063                         // and the outer types as having circular constraints.
44064                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44065                         nonTerminating = true;
44066                         return t.immediateBaseConstraint = noConstraintType;
44067                     }
44068                     constraintDepth++;
44069                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44070                     constraintDepth--;
44071                     if (!popTypeResolution()) {
44072                         if (t.flags & 262144 /* TypeParameter */) {
44073                             var errorNode = getConstraintDeclaration(t);
44074                             if (errorNode) {
44075                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44076                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44077                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44078                                 }
44079                             }
44080                         }
44081                         result = circularConstraintType;
44082                     }
44083                     if (nonTerminating) {
44084                         result = circularConstraintType;
44085                     }
44086                     t.immediateBaseConstraint = result || noConstraintType;
44087                 }
44088                 return t.immediateBaseConstraint;
44089             }
44090             function getBaseConstraint(t) {
44091                 var c = getImmediateBaseConstraint(t);
44092                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44093             }
44094             function computeBaseConstraint(t) {
44095                 if (t.flags & 262144 /* TypeParameter */) {
44096                     var constraint = getConstraintFromTypeParameter(t);
44097                     return t.isThisType || !constraint ?
44098                         constraint :
44099                         getBaseConstraint(constraint);
44100                 }
44101                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44102                     var types = t.types;
44103                     var baseTypes = [];
44104                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44105                         var type_2 = types_7[_i];
44106                         var baseType = getBaseConstraint(type_2);
44107                         if (baseType) {
44108                             baseTypes.push(baseType);
44109                         }
44110                     }
44111                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44112                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44113                             undefined;
44114                 }
44115                 if (t.flags & 4194304 /* Index */) {
44116                     return keyofConstraintType;
44117                 }
44118                 if (t.flags & 8388608 /* IndexedAccess */) {
44119                     var baseObjectType = getBaseConstraint(t.objectType);
44120                     var baseIndexType = getBaseConstraint(t.indexType);
44121                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44122                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44123                 }
44124                 if (t.flags & 16777216 /* Conditional */) {
44125                     var constraint = getConstraintFromConditionalType(t);
44126                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44127                     var result = constraint && getBaseConstraint(constraint);
44128                     constraintDepth--;
44129                     return result;
44130                 }
44131                 if (t.flags & 33554432 /* Substitution */) {
44132                     return getBaseConstraint(t.substitute);
44133                 }
44134                 return t;
44135             }
44136         }
44137         function getApparentTypeOfIntersectionType(type) {
44138             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44139         }
44140         function getResolvedTypeParameterDefault(typeParameter) {
44141             if (!typeParameter.default) {
44142                 if (typeParameter.target) {
44143                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44144                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44145                 }
44146                 else {
44147                     // To block recursion, set the initial value to the resolvingDefaultType.
44148                     typeParameter.default = resolvingDefaultType;
44149                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44150                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44151                     if (typeParameter.default === resolvingDefaultType) {
44152                         // If we have not been called recursively, set the correct default type.
44153                         typeParameter.default = defaultType;
44154                     }
44155                 }
44156             }
44157             else if (typeParameter.default === resolvingDefaultType) {
44158                 // If we are called recursively for this type parameter, mark the default as circular.
44159                 typeParameter.default = circularConstraintType;
44160             }
44161             return typeParameter.default;
44162         }
44163         /**
44164          * Gets the default type for a type parameter.
44165          *
44166          * If the type parameter is the result of an instantiation, this gets the instantiated
44167          * default type of its target. If the type parameter has no default type or the default is
44168          * circular, `undefined` is returned.
44169          */
44170         function getDefaultFromTypeParameter(typeParameter) {
44171             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44172             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44173         }
44174         function hasNonCircularTypeParameterDefault(typeParameter) {
44175             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44176         }
44177         /**
44178          * Indicates whether the declaration of a typeParameter has a default type.
44179          */
44180         function hasTypeParameterDefault(typeParameter) {
44181             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44182         }
44183         function getApparentTypeOfMappedType(type) {
44184             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44185         }
44186         function getResolvedApparentTypeOfMappedType(type) {
44187             var typeVariable = getHomomorphicTypeVariable(type);
44188             if (typeVariable) {
44189                 var constraint = getConstraintOfTypeParameter(typeVariable);
44190                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44191                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44192                 }
44193             }
44194             return type;
44195         }
44196         /**
44197          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44198          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44199          * type itself.
44200          */
44201         function getApparentType(type) {
44202             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44203             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44204                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44205                     t.flags & 132 /* StringLike */ ? globalStringType :
44206                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44207                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44208                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44209                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44210                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44211                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44212                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44213                                                     t;
44214         }
44215         function getReducedApparentType(type) {
44216             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44217             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44218             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44219             // that type may need futher reduction to remove empty intersections.
44220             return getReducedType(getApparentType(getReducedType(type)));
44221         }
44222         function createUnionOrIntersectionProperty(containingType, name) {
44223             var singleProp;
44224             var propSet;
44225             var indexTypes;
44226             var isUnion = containingType.flags & 1048576 /* Union */;
44227             // Flags we want to propagate to the result if they exist in all source symbols
44228             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44229             var syntheticFlag = 4 /* SyntheticMethod */;
44230             var checkFlags = 0;
44231             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44232                 var current = _a[_i];
44233                 var type = getApparentType(current);
44234                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44235                     var prop = getPropertyOfType(type, name);
44236                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44237                     if (prop) {
44238                         if (isUnion) {
44239                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44240                         }
44241                         else {
44242                             optionalFlag &= prop.flags;
44243                         }
44244                         if (!singleProp) {
44245                             singleProp = prop;
44246                         }
44247                         else if (prop !== singleProp) {
44248                             if (!propSet) {
44249                                 propSet = ts.createMap();
44250                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44251                             }
44252                             var id = "" + getSymbolId(prop);
44253                             if (!propSet.has(id)) {
44254                                 propSet.set(id, prop);
44255                             }
44256                         }
44257                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44258                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44259                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44260                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44261                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44262                         if (!isPrototypeProperty(prop)) {
44263                             syntheticFlag = 2 /* SyntheticProperty */;
44264                         }
44265                     }
44266                     else if (isUnion) {
44267                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44268                         if (indexInfo) {
44269                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44270                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44271                         }
44272                         else if (isObjectLiteralType(type)) {
44273                             checkFlags |= 32 /* WritePartial */;
44274                             indexTypes = ts.append(indexTypes, undefinedType);
44275                         }
44276                         else {
44277                             checkFlags |= 16 /* ReadPartial */;
44278                         }
44279                     }
44280                 }
44281             }
44282             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44283                 // No property was found, or, in a union, a property has a private or protected declaration in one
44284                 // constituent, but is missing or has a different declaration in another constituent.
44285                 return undefined;
44286             }
44287             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44288                 return singleProp;
44289             }
44290             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44291             var declarations;
44292             var firstType;
44293             var nameType;
44294             var propTypes = [];
44295             var firstValueDeclaration;
44296             var hasNonUniformValueDeclaration = false;
44297             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44298                 var prop = props_1[_b];
44299                 if (!firstValueDeclaration) {
44300                     firstValueDeclaration = prop.valueDeclaration;
44301                 }
44302                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44303                     hasNonUniformValueDeclaration = true;
44304                 }
44305                 declarations = ts.addRange(declarations, prop.declarations);
44306                 var type = getTypeOfSymbol(prop);
44307                 if (!firstType) {
44308                     firstType = type;
44309                     nameType = getSymbolLinks(prop).nameType;
44310                 }
44311                 else if (type !== firstType) {
44312                     checkFlags |= 64 /* HasNonUniformType */;
44313                 }
44314                 if (isLiteralType(type)) {
44315                     checkFlags |= 128 /* HasLiteralType */;
44316                 }
44317                 if (type.flags & 131072 /* Never */) {
44318                     checkFlags |= 131072 /* HasNeverType */;
44319                 }
44320                 propTypes.push(type);
44321             }
44322             ts.addRange(propTypes, indexTypes);
44323             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44324             result.containingType = containingType;
44325             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44326                 result.valueDeclaration = firstValueDeclaration;
44327                 // Inherit information about parent type.
44328                 if (firstValueDeclaration.symbol.parent) {
44329                     result.parent = firstValueDeclaration.symbol.parent;
44330                 }
44331             }
44332             result.declarations = declarations;
44333             result.nameType = nameType;
44334             if (propTypes.length > 2) {
44335                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44336                 result.checkFlags |= 65536 /* DeferredType */;
44337                 result.deferralParent = containingType;
44338                 result.deferralConstituents = propTypes;
44339             }
44340             else {
44341                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44342             }
44343             return result;
44344         }
44345         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44346         // does not exist in any constituent type. Note that the returned property may only be present in some
44347         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44348         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44349         // and do not appear to be present in the union type.
44350         function getUnionOrIntersectionProperty(type, name) {
44351             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44352             var property = properties.get(name);
44353             if (!property) {
44354                 property = createUnionOrIntersectionProperty(type, name);
44355                 if (property) {
44356                     properties.set(name, property);
44357                 }
44358             }
44359             return property;
44360         }
44361         function getPropertyOfUnionOrIntersectionType(type, name) {
44362             var property = getUnionOrIntersectionProperty(type, name);
44363             // We need to filter out partial properties in union types
44364             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44365         }
44366         /**
44367          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44368          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44369          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44370          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44371          */
44372         function getReducedType(type) {
44373             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44374                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44375             }
44376             else if (type.flags & 2097152 /* Intersection */) {
44377                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44378                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44379                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44380                 }
44381                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44382             }
44383             return type;
44384         }
44385         function getReducedUnionType(unionType) {
44386             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44387             if (reducedTypes === unionType.types) {
44388                 return unionType;
44389             }
44390             var reduced = getUnionType(reducedTypes);
44391             if (reduced.flags & 1048576 /* Union */) {
44392                 reduced.resolvedReducedType = reduced;
44393             }
44394             return reduced;
44395         }
44396         function isNeverReducedProperty(prop) {
44397             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44398         }
44399         function isDiscriminantWithNeverType(prop) {
44400             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44401             // a literal type and none is never, that reduces to never.
44402             return !(prop.flags & 16777216 /* Optional */) &&
44403                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44404                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44405         }
44406         function isConflictingPrivateProperty(prop) {
44407             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44408             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44409         }
44410         function elaborateNeverIntersection(errorInfo, type) {
44411             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44412                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44413                 if (neverProp) {
44414                     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));
44415                 }
44416                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44417                 if (privateProp) {
44418                     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));
44419                 }
44420             }
44421             return errorInfo;
44422         }
44423         /**
44424          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44425          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44426          * Object and Function as appropriate.
44427          *
44428          * @param type a type to look up property from
44429          * @param name a name of property to look up in a given type
44430          */
44431         function getPropertyOfType(type, name) {
44432             type = getReducedApparentType(type);
44433             if (type.flags & 524288 /* Object */) {
44434                 var resolved = resolveStructuredTypeMembers(type);
44435                 var symbol = resolved.members.get(name);
44436                 if (symbol && symbolIsValue(symbol)) {
44437                     return symbol;
44438                 }
44439                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44440                     resolved.callSignatures.length ? globalCallableFunctionType :
44441                         resolved.constructSignatures.length ? globalNewableFunctionType :
44442                             undefined;
44443                 if (functionType) {
44444                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44445                     if (symbol_1) {
44446                         return symbol_1;
44447                     }
44448                 }
44449                 return getPropertyOfObjectType(globalObjectType, name);
44450             }
44451             if (type.flags & 3145728 /* UnionOrIntersection */) {
44452                 return getPropertyOfUnionOrIntersectionType(type, name);
44453             }
44454             return undefined;
44455         }
44456         function getSignaturesOfStructuredType(type, kind) {
44457             if (type.flags & 3670016 /* StructuredType */) {
44458                 var resolved = resolveStructuredTypeMembers(type);
44459                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44460             }
44461             return ts.emptyArray;
44462         }
44463         /**
44464          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44465          * maps primitive types and type parameters are to their apparent types.
44466          */
44467         function getSignaturesOfType(type, kind) {
44468             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44469         }
44470         function getIndexInfoOfStructuredType(type, kind) {
44471             if (type.flags & 3670016 /* StructuredType */) {
44472                 var resolved = resolveStructuredTypeMembers(type);
44473                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44474             }
44475         }
44476         function getIndexTypeOfStructuredType(type, kind) {
44477             var info = getIndexInfoOfStructuredType(type, kind);
44478             return info && info.type;
44479         }
44480         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44481         // maps primitive types and type parameters are to their apparent types.
44482         function getIndexInfoOfType(type, kind) {
44483             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44484         }
44485         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44486         // maps primitive types and type parameters are to their apparent types.
44487         function getIndexTypeOfType(type, kind) {
44488             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44489         }
44490         function getImplicitIndexTypeOfType(type, kind) {
44491             if (isObjectTypeWithInferableIndex(type)) {
44492                 var propTypes = [];
44493                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44494                     var prop = _a[_i];
44495                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44496                         propTypes.push(getTypeOfSymbol(prop));
44497                     }
44498                 }
44499                 if (kind === 0 /* String */) {
44500                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44501                 }
44502                 if (propTypes.length) {
44503                     return getUnionType(propTypes);
44504                 }
44505             }
44506             return undefined;
44507         }
44508         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44509         // type checking functions).
44510         function getTypeParametersFromDeclaration(declaration) {
44511             var result;
44512             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44513                 var node = _a[_i];
44514                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44515             }
44516             return result;
44517         }
44518         function symbolsToArray(symbols) {
44519             var result = [];
44520             symbols.forEach(function (symbol, id) {
44521                 if (!isReservedMemberName(id)) {
44522                     result.push(symbol);
44523                 }
44524             });
44525             return result;
44526         }
44527         function isJSDocOptionalParameter(node) {
44528             return ts.isInJSFile(node) && (
44529             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44530             node.type && node.type.kind === 299 /* JSDocOptionalType */
44531                 || ts.getJSDocParameterTags(node).some(function (_a) {
44532                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44533                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44534                 }));
44535         }
44536         function tryFindAmbientModule(moduleName, withAugmentations) {
44537             if (ts.isExternalModuleNameRelative(moduleName)) {
44538                 return undefined;
44539             }
44540             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44541             // merged symbol is module declaration symbol combined with all augmentations
44542             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44543         }
44544         function isOptionalParameter(node) {
44545             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44546                 return true;
44547             }
44548             if (node.initializer) {
44549                 var signature = getSignatureFromDeclaration(node.parent);
44550                 var parameterIndex = node.parent.parameters.indexOf(node);
44551                 ts.Debug.assert(parameterIndex >= 0);
44552                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44553             }
44554             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44555             if (iife) {
44556                 return !node.type &&
44557                     !node.dotDotDotToken &&
44558                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44559             }
44560             return false;
44561         }
44562         function isOptionalJSDocParameterTag(node) {
44563             if (!ts.isJSDocParameterTag(node)) {
44564                 return false;
44565             }
44566             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44567             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44568         }
44569         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44570             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44571         }
44572         /**
44573          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44574          * parameters.
44575          */
44576         function getMinTypeArgumentCount(typeParameters) {
44577             var minTypeArgumentCount = 0;
44578             if (typeParameters) {
44579                 for (var i = 0; i < typeParameters.length; i++) {
44580                     if (!hasTypeParameterDefault(typeParameters[i])) {
44581                         minTypeArgumentCount = i + 1;
44582                     }
44583                 }
44584             }
44585             return minTypeArgumentCount;
44586         }
44587         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44588             var numTypeParameters = ts.length(typeParameters);
44589             if (!numTypeParameters) {
44590                 return [];
44591             }
44592             var numTypeArguments = ts.length(typeArguments);
44593             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44594                 var result = typeArguments ? typeArguments.slice() : [];
44595                 // Map invalid forward references in default types to the error type
44596                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44597                     result[i] = errorType;
44598                 }
44599                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44600                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44601                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44602                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44603                         defaultType = anyType;
44604                     }
44605                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44606                 }
44607                 result.length = typeParameters.length;
44608                 return result;
44609             }
44610             return typeArguments && typeArguments.slice();
44611         }
44612         function getSignatureFromDeclaration(declaration) {
44613             var links = getNodeLinks(declaration);
44614             if (!links.resolvedSignature) {
44615                 var parameters = [];
44616                 var flags = 0 /* None */;
44617                 var minArgumentCount = 0;
44618                 var thisParameter = void 0;
44619                 var hasThisParameter = false;
44620                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44621                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44622                 var isUntypedSignatureInJSFile = !iife &&
44623                     ts.isInJSFile(declaration) &&
44624                     ts.isValueSignatureDeclaration(declaration) &&
44625                     !ts.hasJSDocParameterTags(declaration) &&
44626                     !ts.getJSDocType(declaration);
44627                 if (isUntypedSignatureInJSFile) {
44628                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44629                 }
44630                 // If this is a JSDoc construct signature, then skip the first parameter in the
44631                 // parameter list.  The first parameter represents the return type of the construct
44632                 // signature.
44633                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44634                     var param = declaration.parameters[i];
44635                     var paramSymbol = param.symbol;
44636                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44637                     // Include parameter symbol instead of property symbol in the signature
44638                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44639                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44640                         paramSymbol = resolvedSymbol;
44641                     }
44642                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44643                         hasThisParameter = true;
44644                         thisParameter = param.symbol;
44645                     }
44646                     else {
44647                         parameters.push(paramSymbol);
44648                     }
44649                     if (type && type.kind === 187 /* LiteralType */) {
44650                         flags |= 2 /* HasLiteralTypes */;
44651                     }
44652                     // Record a new minimum argument count if this is not an optional parameter
44653                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44654                         param.initializer || param.questionToken || param.dotDotDotToken ||
44655                         iife && parameters.length > iife.arguments.length && !type ||
44656                         isJSDocOptionalParameter(param);
44657                     if (!isOptionalParameter_1) {
44658                         minArgumentCount = parameters.length;
44659                     }
44660                 }
44661                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44662                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44663                     !hasNonBindableDynamicName(declaration) &&
44664                     (!hasThisParameter || !thisParameter)) {
44665                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44666                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44667                     if (other) {
44668                         thisParameter = getAnnotatedAccessorThisParameter(other);
44669                     }
44670                 }
44671                 var classType = declaration.kind === 162 /* Constructor */ ?
44672                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44673                     : undefined;
44674                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44675                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44676                     flags |= 1 /* HasRestParameter */;
44677                 }
44678                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44679                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44680             }
44681             return links.resolvedSignature;
44682         }
44683         /**
44684          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44685          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44686          * OR
44687          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44688          */
44689         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44690             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44691                 return false;
44692             }
44693             var lastParam = ts.lastOrUndefined(declaration.parameters);
44694             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44695             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44696                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44697             });
44698             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44699             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44700             if (lastParamVariadicType) {
44701                 // Replace the last parameter with a rest parameter.
44702                 parameters.pop();
44703             }
44704             parameters.push(syntheticArgsSymbol);
44705             return true;
44706         }
44707         function getSignatureOfTypeTag(node) {
44708             // should be attached to a function declaration or expression
44709             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44710                 return undefined;
44711             var typeTag = ts.getJSDocTypeTag(node);
44712             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44713             return signature && getErasedSignature(signature);
44714         }
44715         function getReturnTypeOfTypeTag(node) {
44716             var signature = getSignatureOfTypeTag(node);
44717             return signature && getReturnTypeOfSignature(signature);
44718         }
44719         function containsArgumentsReference(declaration) {
44720             var links = getNodeLinks(declaration);
44721             if (links.containsArgumentsReference === undefined) {
44722                 if (links.flags & 8192 /* CaptureArguments */) {
44723                     links.containsArgumentsReference = true;
44724                 }
44725                 else {
44726                     links.containsArgumentsReference = traverse(declaration.body);
44727                 }
44728             }
44729             return links.containsArgumentsReference;
44730             function traverse(node) {
44731                 if (!node)
44732                     return false;
44733                 switch (node.kind) {
44734                     case 75 /* Identifier */:
44735                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44736                     case 159 /* PropertyDeclaration */:
44737                     case 161 /* MethodDeclaration */:
44738                     case 163 /* GetAccessor */:
44739                     case 164 /* SetAccessor */:
44740                         return node.name.kind === 154 /* ComputedPropertyName */
44741                             && traverse(node.name);
44742                     default:
44743                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44744                 }
44745             }
44746         }
44747         function getSignaturesOfSymbol(symbol) {
44748             if (!symbol)
44749                 return ts.emptyArray;
44750             var result = [];
44751             for (var i = 0; i < symbol.declarations.length; i++) {
44752                 var decl = symbol.declarations[i];
44753                 if (!ts.isFunctionLike(decl))
44754                     continue;
44755                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44756                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44757                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44758                 if (i > 0 && decl.body) {
44759                     var previous = symbol.declarations[i - 1];
44760                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44761                         continue;
44762                     }
44763                 }
44764                 result.push(getSignatureFromDeclaration(decl));
44765             }
44766             return result;
44767         }
44768         function resolveExternalModuleTypeByLiteral(name) {
44769             var moduleSym = resolveExternalModuleName(name, name);
44770             if (moduleSym) {
44771                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44772                 if (resolvedModuleSymbol) {
44773                     return getTypeOfSymbol(resolvedModuleSymbol);
44774                 }
44775             }
44776             return anyType;
44777         }
44778         function getThisTypeOfSignature(signature) {
44779             if (signature.thisParameter) {
44780                 return getTypeOfSymbol(signature.thisParameter);
44781             }
44782         }
44783         function getTypePredicateOfSignature(signature) {
44784             if (!signature.resolvedTypePredicate) {
44785                 if (signature.target) {
44786                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44787                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44788                 }
44789                 else if (signature.unionSignatures) {
44790                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44791                 }
44792                 else {
44793                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44794                     var jsdocPredicate = void 0;
44795                     if (!type && ts.isInJSFile(signature.declaration)) {
44796                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44797                         if (jsdocSignature && signature !== jsdocSignature) {
44798                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44799                         }
44800                     }
44801                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44802                         createTypePredicateFromTypePredicateNode(type, signature) :
44803                         jsdocPredicate || noTypePredicate;
44804                 }
44805                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44806             }
44807             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44808         }
44809         function createTypePredicateFromTypePredicateNode(node, signature) {
44810             var parameterName = node.parameterName;
44811             var type = node.type && getTypeFromTypeNode(node.type);
44812             return parameterName.kind === 183 /* ThisType */ ?
44813                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44814                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44815         }
44816         function getReturnTypeOfSignature(signature) {
44817             if (!signature.resolvedReturnType) {
44818                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44819                     return errorType;
44820                 }
44821                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44822                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44823                         getReturnTypeFromAnnotation(signature.declaration) ||
44824                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
44825                 if (signature.flags & 4 /* IsInnerCallChain */) {
44826                     type = addOptionalTypeMarker(type);
44827                 }
44828                 else if (signature.flags & 8 /* IsOuterCallChain */) {
44829                     type = getOptionalType(type);
44830                 }
44831                 if (!popTypeResolution()) {
44832                     if (signature.declaration) {
44833                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
44834                         if (typeNode) {
44835                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
44836                         }
44837                         else if (noImplicitAny) {
44838                             var declaration = signature.declaration;
44839                             var name = ts.getNameOfDeclaration(declaration);
44840                             if (name) {
44841                                 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));
44842                             }
44843                             else {
44844                                 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);
44845                             }
44846                         }
44847                     }
44848                     type = anyType;
44849                 }
44850                 signature.resolvedReturnType = type;
44851             }
44852             return signature.resolvedReturnType;
44853         }
44854         function getReturnTypeFromAnnotation(declaration) {
44855             if (declaration.kind === 162 /* Constructor */) {
44856                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
44857             }
44858             if (ts.isJSDocConstructSignature(declaration)) {
44859                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
44860             }
44861             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
44862             if (typeNode) {
44863                 return getTypeFromTypeNode(typeNode);
44864             }
44865             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
44866                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
44867                 if (jsDocType) {
44868                     return jsDocType;
44869                 }
44870                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
44871                 var setterType = getAnnotatedAccessorType(setter);
44872                 if (setterType) {
44873                     return setterType;
44874                 }
44875             }
44876             return getReturnTypeOfTypeTag(declaration);
44877         }
44878         function isResolvingReturnTypeOfSignature(signature) {
44879             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
44880         }
44881         function getRestTypeOfSignature(signature) {
44882             return tryGetRestTypeOfSignature(signature) || anyType;
44883         }
44884         function tryGetRestTypeOfSignature(signature) {
44885             if (signatureHasRestParameter(signature)) {
44886                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
44887                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
44888                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
44889             }
44890             return undefined;
44891         }
44892         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
44893             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
44894             if (inferredTypeParameters) {
44895                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
44896                 if (returnSignature) {
44897                     var newReturnSignature = cloneSignature(returnSignature);
44898                     newReturnSignature.typeParameters = inferredTypeParameters;
44899                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
44900                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
44901                     return newInstantiatedSignature;
44902                 }
44903             }
44904             return instantiatedSignature;
44905         }
44906         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
44907             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
44908             var id = getTypeListId(typeArguments);
44909             var instantiation = instantiations.get(id);
44910             if (!instantiation) {
44911                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
44912             }
44913             return instantiation;
44914         }
44915         function createSignatureInstantiation(signature, typeArguments) {
44916             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
44917         }
44918         function createSignatureTypeMapper(signature, typeArguments) {
44919             return createTypeMapper(signature.typeParameters, typeArguments);
44920         }
44921         function getErasedSignature(signature) {
44922             return signature.typeParameters ?
44923                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
44924                 signature;
44925         }
44926         function createErasedSignature(signature) {
44927             // Create an instantiation of the signature where all type arguments are the any type.
44928             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
44929         }
44930         function getCanonicalSignature(signature) {
44931             return signature.typeParameters ?
44932                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
44933                 signature;
44934         }
44935         function createCanonicalSignature(signature) {
44936             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
44937             // its original. When a generic class or interface is instantiated, each generic method in the class or
44938             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
44939             // where different generations of the same type parameter are in scope). This leads to a lot of new type
44940             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
44941             // that uses the original type identities for all unconstrained type parameters.
44942             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
44943         }
44944         function getBaseSignature(signature) {
44945             var typeParameters = signature.typeParameters;
44946             if (typeParameters) {
44947                 var typeEraser_1 = createTypeEraser(typeParameters);
44948                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
44949                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
44950             }
44951             return signature;
44952         }
44953         function getOrCreateTypeFromSignature(signature) {
44954             // There are two ways to declare a construct signature, one is by declaring a class constructor
44955             // using the constructor keyword, and the other is declaring a bare construct signature in an
44956             // object type literal or interface (using the new keyword). Each way of declaring a constructor
44957             // will result in a different declaration kind.
44958             if (!signature.isolatedSignatureType) {
44959                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
44960                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
44961                 var type = createObjectType(16 /* Anonymous */);
44962                 type.members = emptySymbols;
44963                 type.properties = ts.emptyArray;
44964                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
44965                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
44966                 signature.isolatedSignatureType = type;
44967             }
44968             return signature.isolatedSignatureType;
44969         }
44970         function getIndexSymbol(symbol) {
44971             return symbol.members.get("__index" /* Index */);
44972         }
44973         function getIndexDeclarationOfSymbol(symbol, kind) {
44974             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
44975             var indexSymbol = getIndexSymbol(symbol);
44976             if (indexSymbol) {
44977                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
44978                     var decl = _a[_i];
44979                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
44980                     if (node.parameters.length === 1) {
44981                         var parameter = node.parameters[0];
44982                         if (parameter.type && parameter.type.kind === syntaxKind) {
44983                             return node;
44984                         }
44985                     }
44986                 }
44987             }
44988             return undefined;
44989         }
44990         function createIndexInfo(type, isReadonly, declaration) {
44991             return { type: type, isReadonly: isReadonly, declaration: declaration };
44992         }
44993         function getIndexInfoOfSymbol(symbol, kind) {
44994             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
44995             if (declaration) {
44996                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
44997             }
44998             return undefined;
44999         }
45000         function getConstraintDeclaration(type) {
45001             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45002         }
45003         function getInferredTypeParameterConstraint(typeParameter) {
45004             var inferences;
45005             if (typeParameter.symbol) {
45006                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45007                     var declaration = _a[_i];
45008                     if (declaration.parent.kind === 181 /* InferType */) {
45009                         // When an 'infer T' declaration is immediately contained in a type reference node
45010                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45011                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45012                         // present, we form an intersection of the inferred constraint types.
45013                         var grandParent = declaration.parent.parent;
45014                         if (grandParent.kind === 169 /* TypeReference */) {
45015                             var typeReference = grandParent;
45016                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45017                             if (typeParameters) {
45018                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45019                                 if (index < typeParameters.length) {
45020                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45021                                     if (declaredConstraint) {
45022                                         // Type parameter constraints can reference other type parameters so
45023                                         // constraints need to be instantiated. If instantiation produces the
45024                                         // type parameter itself, we discard that inference. For example, in
45025                                         //   type Foo<T extends string, U extends T> = [T, U];
45026                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45027                                         // the instantiated constraint for U is X, so we discard that inference.
45028                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45029                                         var constraint = instantiateType(declaredConstraint, mapper);
45030                                         if (constraint !== typeParameter) {
45031                                             inferences = ts.append(inferences, constraint);
45032                                         }
45033                                     }
45034                                 }
45035                             }
45036                         }
45037                         // When an 'infer T' declaration is immediately contained in a rest parameter
45038                         // declaration, we infer an 'unknown[]' constraint.
45039                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45040                             inferences = ts.append(inferences, createArrayType(unknownType));
45041                         }
45042                     }
45043                 }
45044             }
45045             return inferences && getIntersectionType(inferences);
45046         }
45047         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45048         function getConstraintFromTypeParameter(typeParameter) {
45049             if (!typeParameter.constraint) {
45050                 if (typeParameter.target) {
45051                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45052                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45053                 }
45054                 else {
45055                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45056                     if (!constraintDeclaration) {
45057                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45058                     }
45059                     else {
45060                         var type = getTypeFromTypeNode(constraintDeclaration);
45061                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45062                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45063                             // use unknown otherwise
45064                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45065                         }
45066                         typeParameter.constraint = type;
45067                     }
45068                 }
45069             }
45070             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45071         }
45072         function getParentSymbolOfTypeParameter(typeParameter) {
45073             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45074             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45075             return host && getSymbolOfNode(host);
45076         }
45077         function getTypeListId(types) {
45078             var result = "";
45079             if (types) {
45080                 var length_4 = types.length;
45081                 var i = 0;
45082                 while (i < length_4) {
45083                     var startId = types[i].id;
45084                     var count = 1;
45085                     while (i + count < length_4 && types[i + count].id === startId + count) {
45086                         count++;
45087                     }
45088                     if (result.length) {
45089                         result += ",";
45090                     }
45091                     result += startId;
45092                     if (count > 1) {
45093                         result += ":" + count;
45094                     }
45095                     i += count;
45096                 }
45097             }
45098             return result;
45099         }
45100         // This function is used to propagate certain flags when creating new object type references and union types.
45101         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45102         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45103         // that care about the presence of such types at arbitrary depth in a containing type.
45104         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45105             var result = 0;
45106             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45107                 var type = types_8[_i];
45108                 if (!(type.flags & excludeKinds)) {
45109                     result |= ts.getObjectFlags(type);
45110                 }
45111             }
45112             return result & 3670016 /* PropagatingFlags */;
45113         }
45114         function createTypeReference(target, typeArguments) {
45115             var id = getTypeListId(typeArguments);
45116             var type = target.instantiations.get(id);
45117             if (!type) {
45118                 type = createObjectType(4 /* Reference */, target.symbol);
45119                 target.instantiations.set(id, type);
45120                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45121                 type.target = target;
45122                 type.resolvedTypeArguments = typeArguments;
45123             }
45124             return type;
45125         }
45126         function cloneTypeReference(source) {
45127             var type = createType(source.flags);
45128             type.symbol = source.symbol;
45129             type.objectFlags = source.objectFlags;
45130             type.target = source.target;
45131             type.resolvedTypeArguments = source.resolvedTypeArguments;
45132             return type;
45133         }
45134         function createDeferredTypeReference(target, node, mapper) {
45135             var aliasSymbol = getAliasSymbolForTypeNode(node);
45136             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45137             var type = createObjectType(4 /* Reference */, target.symbol);
45138             type.target = target;
45139             type.node = node;
45140             type.mapper = mapper;
45141             type.aliasSymbol = aliasSymbol;
45142             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45143             return type;
45144         }
45145         function getTypeArguments(type) {
45146             var _a, _b;
45147             if (!type.resolvedTypeArguments) {
45148                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45149                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45150                 }
45151                 var node = type.node;
45152                 var typeArguments = !node ? ts.emptyArray :
45153                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45154                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45155                             ts.map(node.elementTypes, getTypeFromTypeNode);
45156                 if (popTypeResolution()) {
45157                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45158                 }
45159                 else {
45160                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45161                     error(type.node || currentNode, type.target.symbol
45162                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45163                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45164                 }
45165             }
45166             return type.resolvedTypeArguments;
45167         }
45168         function getTypeReferenceArity(type) {
45169             return ts.length(type.target.typeParameters);
45170         }
45171         /**
45172          * Get type from type-reference that reference to class or interface
45173          */
45174         function getTypeFromClassOrInterfaceReference(node, symbol) {
45175             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45176             var typeParameters = type.localTypeParameters;
45177             if (typeParameters) {
45178                 var numTypeArguments = ts.length(node.typeArguments);
45179                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45180                 var isJs = ts.isInJSFile(node);
45181                 var isJsImplicitAny = !noImplicitAny && isJs;
45182                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45183                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45184                     var diag = minTypeArgumentCount === typeParameters.length ?
45185                         missingAugmentsTag ?
45186                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45187                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45188                         missingAugmentsTag ?
45189                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45190                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45191                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45192                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45193                     if (!isJs) {
45194                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45195                         return errorType;
45196                     }
45197                 }
45198                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45199                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45200                 }
45201                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45202                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45203                 // of the class or interface.
45204                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45205                 return createTypeReference(type, typeArguments);
45206             }
45207             return checkNoTypeArguments(node, symbol) ? type : errorType;
45208         }
45209         function getTypeAliasInstantiation(symbol, typeArguments) {
45210             var type = getDeclaredTypeOfSymbol(symbol);
45211             var links = getSymbolLinks(symbol);
45212             var typeParameters = links.typeParameters;
45213             var id = getTypeListId(typeArguments);
45214             var instantiation = links.instantiations.get(id);
45215             if (!instantiation) {
45216                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45217             }
45218             return instantiation;
45219         }
45220         /**
45221          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45222          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45223          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45224          */
45225         function getTypeFromTypeAliasReference(node, symbol) {
45226             var type = getDeclaredTypeOfSymbol(symbol);
45227             var typeParameters = getSymbolLinks(symbol).typeParameters;
45228             if (typeParameters) {
45229                 var numTypeArguments = ts.length(node.typeArguments);
45230                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45231                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45232                     error(node, minTypeArgumentCount === typeParameters.length ?
45233                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45234                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45235                     return errorType;
45236                 }
45237                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45238             }
45239             return checkNoTypeArguments(node, symbol) ? type : errorType;
45240         }
45241         function getTypeReferenceName(node) {
45242             switch (node.kind) {
45243                 case 169 /* TypeReference */:
45244                     return node.typeName;
45245                 case 216 /* ExpressionWithTypeArguments */:
45246                     // We only support expressions that are simple qualified names. For other
45247                     // expressions this produces undefined.
45248                     var expr = node.expression;
45249                     if (ts.isEntityNameExpression(expr)) {
45250                         return expr;
45251                     }
45252                 // fall through;
45253             }
45254             return undefined;
45255         }
45256         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45257             if (!typeReferenceName) {
45258                 return unknownSymbol;
45259             }
45260             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45261         }
45262         function getTypeReferenceType(node, symbol) {
45263             if (symbol === unknownSymbol) {
45264                 return errorType;
45265             }
45266             symbol = getExpandoSymbol(symbol) || symbol;
45267             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45268                 return getTypeFromClassOrInterfaceReference(node, symbol);
45269             }
45270             if (symbol.flags & 524288 /* TypeAlias */) {
45271                 return getTypeFromTypeAliasReference(node, symbol);
45272             }
45273             // Get type from reference to named type that cannot be generic (enum or type parameter)
45274             var res = tryGetDeclaredTypeOfSymbol(symbol);
45275             if (res) {
45276                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45277             }
45278             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45279                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45280                 if (jsdocType) {
45281                     return jsdocType;
45282                 }
45283                 else {
45284                     // Resolve the type reference as a Type for the purpose of reporting errors.
45285                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45286                     return getTypeOfSymbol(symbol);
45287                 }
45288             }
45289             return errorType;
45290         }
45291         /**
45292          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45293          * Note: If the value is imported from commonjs, it should really be an alias,
45294          * but this function's special-case code fakes alias resolution as well.
45295          */
45296         function getTypeFromJSDocValueReference(node, symbol) {
45297             var links = getNodeLinks(node);
45298             if (!links.resolvedJSDocType) {
45299                 var valueType = getTypeOfSymbol(symbol);
45300                 var typeType = valueType;
45301                 if (symbol.valueDeclaration) {
45302                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45303                     var isRequireAlias = false;
45304                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45305                         var expr = decl.initializer;
45306                         // skip past entity names, eg `require("x").a.b.c`
45307                         while (ts.isPropertyAccessExpression(expr)) {
45308                             expr = expr.expression;
45309                         }
45310                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45311                     }
45312                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45313                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45314                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45315                         typeType = getTypeReferenceType(node, valueType.symbol);
45316                     }
45317                 }
45318                 links.resolvedJSDocType = typeType;
45319             }
45320             return links.resolvedJSDocType;
45321         }
45322         function getSubstitutionType(baseType, substitute) {
45323             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45324                 return baseType;
45325             }
45326             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45327             var cached = substitutionTypes.get(id);
45328             if (cached) {
45329                 return cached;
45330             }
45331             var result = createType(33554432 /* Substitution */);
45332             result.baseType = baseType;
45333             result.substitute = substitute;
45334             substitutionTypes.set(id, result);
45335             return result;
45336         }
45337         function isUnaryTupleTypeNode(node) {
45338             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45339         }
45340         function getImpliedConstraint(type, checkNode, extendsNode) {
45341             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45342                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45343                     undefined;
45344         }
45345         function getConditionalFlowTypeOfType(type, node) {
45346             var constraints;
45347             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45348                 var parent = node.parent;
45349                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45350                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45351                     if (constraint) {
45352                         constraints = ts.append(constraints, constraint);
45353                     }
45354                 }
45355                 node = parent;
45356             }
45357             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45358         }
45359         function isJSDocTypeReference(node) {
45360             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45361         }
45362         function checkNoTypeArguments(node, symbol) {
45363             if (node.typeArguments) {
45364                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45365                 return false;
45366             }
45367             return true;
45368         }
45369         function getIntendedTypeFromJSDocTypeReference(node) {
45370             if (ts.isIdentifier(node.typeName)) {
45371                 var typeArgs = node.typeArguments;
45372                 switch (node.typeName.escapedText) {
45373                     case "String":
45374                         checkNoTypeArguments(node);
45375                         return stringType;
45376                     case "Number":
45377                         checkNoTypeArguments(node);
45378                         return numberType;
45379                     case "Boolean":
45380                         checkNoTypeArguments(node);
45381                         return booleanType;
45382                     case "Void":
45383                         checkNoTypeArguments(node);
45384                         return voidType;
45385                     case "Undefined":
45386                         checkNoTypeArguments(node);
45387                         return undefinedType;
45388                     case "Null":
45389                         checkNoTypeArguments(node);
45390                         return nullType;
45391                     case "Function":
45392                     case "function":
45393                         checkNoTypeArguments(node);
45394                         return globalFunctionType;
45395                     case "array":
45396                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45397                     case "promise":
45398                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45399                     case "Object":
45400                         if (typeArgs && typeArgs.length === 2) {
45401                             if (ts.isJSDocIndexSignature(node)) {
45402                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45403                                 var target = getTypeFromTypeNode(typeArgs[1]);
45404                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45405                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45406                             }
45407                             return anyType;
45408                         }
45409                         checkNoTypeArguments(node);
45410                         return !noImplicitAny ? anyType : undefined;
45411                 }
45412             }
45413         }
45414         function getTypeFromJSDocNullableTypeNode(node) {
45415             var type = getTypeFromTypeNode(node.type);
45416             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45417         }
45418         function getTypeFromTypeReference(node) {
45419             var links = getNodeLinks(node);
45420             if (!links.resolvedType) {
45421                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45422                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45423                     links.resolvedSymbol = unknownSymbol;
45424                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45425                 }
45426                 var symbol = void 0;
45427                 var type = void 0;
45428                 var meaning = 788968 /* Type */;
45429                 if (isJSDocTypeReference(node)) {
45430                     type = getIntendedTypeFromJSDocTypeReference(node);
45431                     if (!type) {
45432                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45433                         if (symbol === unknownSymbol) {
45434                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45435                         }
45436                         else {
45437                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45438                         }
45439                         type = getTypeReferenceType(node, symbol);
45440                     }
45441                 }
45442                 if (!type) {
45443                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45444                     type = getTypeReferenceType(node, symbol);
45445                 }
45446                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45447                 // type reference in checkTypeReferenceNode.
45448                 links.resolvedSymbol = symbol;
45449                 links.resolvedType = type;
45450             }
45451             return links.resolvedType;
45452         }
45453         function typeArgumentsFromTypeReferenceNode(node) {
45454             return ts.map(node.typeArguments, getTypeFromTypeNode);
45455         }
45456         function getTypeFromTypeQueryNode(node) {
45457             var links = getNodeLinks(node);
45458             if (!links.resolvedType) {
45459                 // TypeScript 1.0 spec (April 2014): 3.6.3
45460                 // The expression is processed as an identifier expression (section 4.3)
45461                 // or property access expression(section 4.10),
45462                 // the widened type(section 3.9) of which becomes the result.
45463                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45464             }
45465             return links.resolvedType;
45466         }
45467         function getTypeOfGlobalSymbol(symbol, arity) {
45468             function getTypeDeclaration(symbol) {
45469                 var declarations = symbol.declarations;
45470                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45471                     var declaration = declarations_3[_i];
45472                     switch (declaration.kind) {
45473                         case 245 /* ClassDeclaration */:
45474                         case 246 /* InterfaceDeclaration */:
45475                         case 248 /* EnumDeclaration */:
45476                             return declaration;
45477                     }
45478                 }
45479             }
45480             if (!symbol) {
45481                 return arity ? emptyGenericType : emptyObjectType;
45482             }
45483             var type = getDeclaredTypeOfSymbol(symbol);
45484             if (!(type.flags & 524288 /* Object */)) {
45485                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45486                 return arity ? emptyGenericType : emptyObjectType;
45487             }
45488             if (ts.length(type.typeParameters) !== arity) {
45489                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45490                 return arity ? emptyGenericType : emptyObjectType;
45491             }
45492             return type;
45493         }
45494         function getGlobalValueSymbol(name, reportErrors) {
45495             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45496         }
45497         function getGlobalTypeSymbol(name, reportErrors) {
45498             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45499         }
45500         function getGlobalSymbol(name, meaning, diagnostic) {
45501             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45502             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45503         }
45504         function getGlobalType(name, arity, reportErrors) {
45505             var symbol = getGlobalTypeSymbol(name, reportErrors);
45506             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45507         }
45508         function getGlobalTypedPropertyDescriptorType() {
45509             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45510         }
45511         function getGlobalTemplateStringsArrayType() {
45512             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45513         }
45514         function getGlobalImportMetaType() {
45515             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45516         }
45517         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45518             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45519         }
45520         function getGlobalESSymbolType(reportErrors) {
45521             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45522         }
45523         function getGlobalPromiseType(reportErrors) {
45524             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45525         }
45526         function getGlobalPromiseLikeType(reportErrors) {
45527             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45528         }
45529         function getGlobalPromiseConstructorSymbol(reportErrors) {
45530             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45531         }
45532         function getGlobalPromiseConstructorLikeType(reportErrors) {
45533             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45534         }
45535         function getGlobalAsyncIterableType(reportErrors) {
45536             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45537         }
45538         function getGlobalAsyncIteratorType(reportErrors) {
45539             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45540         }
45541         function getGlobalAsyncIterableIteratorType(reportErrors) {
45542             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45543         }
45544         function getGlobalAsyncGeneratorType(reportErrors) {
45545             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45546         }
45547         function getGlobalIterableType(reportErrors) {
45548             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45549         }
45550         function getGlobalIteratorType(reportErrors) {
45551             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45552         }
45553         function getGlobalIterableIteratorType(reportErrors) {
45554             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45555         }
45556         function getGlobalGeneratorType(reportErrors) {
45557             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45558         }
45559         function getGlobalIteratorYieldResultType(reportErrors) {
45560             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45561         }
45562         function getGlobalIteratorReturnResultType(reportErrors) {
45563             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45564         }
45565         function getGlobalTypeOrUndefined(name, arity) {
45566             if (arity === void 0) { arity = 0; }
45567             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45568             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45569         }
45570         function getGlobalExtractSymbol() {
45571             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45572         }
45573         function getGlobalOmitSymbol() {
45574             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45575         }
45576         function getGlobalBigIntType(reportErrors) {
45577             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45578         }
45579         /**
45580          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45581          */
45582         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45583             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45584         }
45585         function createTypedPropertyDescriptorType(propertyType) {
45586             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45587         }
45588         function createIterableType(iteratedType) {
45589             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45590         }
45591         function createArrayType(elementType, readonly) {
45592             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45593         }
45594         function getArrayOrTupleTargetType(node) {
45595             var readonly = isReadonlyTypeOperator(node.parent);
45596             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45597                 return readonly ? globalReadonlyArrayType : globalArrayType;
45598             }
45599             var lastElement = ts.lastOrUndefined(node.elementTypes);
45600             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45601             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45602             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45603         }
45604         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45605         // because it is possibly contained in a circular chain of eagerly resolved types.
45606         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45607             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45608                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45609                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45610         }
45611         // Return true when the given node is transitively contained in type constructs that eagerly
45612         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45613         // of type aliases are eagerly resolved.
45614         function isResolvedByTypeAlias(node) {
45615             var parent = node.parent;
45616             switch (parent.kind) {
45617                 case 182 /* ParenthesizedType */:
45618                 case 169 /* TypeReference */:
45619                 case 178 /* UnionType */:
45620                 case 179 /* IntersectionType */:
45621                 case 185 /* IndexedAccessType */:
45622                 case 180 /* ConditionalType */:
45623                 case 184 /* TypeOperator */:
45624                 case 174 /* ArrayType */:
45625                 case 175 /* TupleType */:
45626                     return isResolvedByTypeAlias(parent);
45627                 case 247 /* TypeAliasDeclaration */:
45628                     return true;
45629             }
45630             return false;
45631         }
45632         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45633         // of a type alias.
45634         function mayResolveTypeAlias(node) {
45635             switch (node.kind) {
45636                 case 169 /* TypeReference */:
45637                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45638                 case 172 /* TypeQuery */:
45639                     return true;
45640                 case 184 /* TypeOperator */:
45641                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45642                 case 182 /* ParenthesizedType */:
45643                 case 176 /* OptionalType */:
45644                 case 299 /* JSDocOptionalType */:
45645                 case 297 /* JSDocNullableType */:
45646                 case 298 /* JSDocNonNullableType */:
45647                 case 294 /* JSDocTypeExpression */:
45648                     return mayResolveTypeAlias(node.type);
45649                 case 177 /* RestType */:
45650                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45651                 case 178 /* UnionType */:
45652                 case 179 /* IntersectionType */:
45653                     return ts.some(node.types, mayResolveTypeAlias);
45654                 case 185 /* IndexedAccessType */:
45655                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45656                 case 180 /* ConditionalType */:
45657                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45658                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45659             }
45660             return false;
45661         }
45662         function getTypeFromArrayOrTupleTypeNode(node) {
45663             var links = getNodeLinks(node);
45664             if (!links.resolvedType) {
45665                 var target = getArrayOrTupleTargetType(node);
45666                 if (target === emptyGenericType) {
45667                     links.resolvedType = emptyObjectType;
45668                 }
45669                 else if (isDeferredTypeReferenceNode(node)) {
45670                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45671                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45672                 }
45673                 else {
45674                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45675                     links.resolvedType = createTypeReference(target, elementTypes);
45676                 }
45677             }
45678             return links.resolvedType;
45679         }
45680         function isReadonlyTypeOperator(node) {
45681             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45682         }
45683         // We represent tuple types as type references to synthesized generic interface types created by
45684         // this function. The types are of the form:
45685         //
45686         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45687         //
45688         // Note that the generic type created by this function has no symbol associated with it. The same
45689         // is true for each of the synthesized type parameters.
45690         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45691             var typeParameters;
45692             var properties = [];
45693             var maxLength = hasRestElement ? arity - 1 : arity;
45694             if (arity) {
45695                 typeParameters = new Array(arity);
45696                 for (var i = 0; i < arity; i++) {
45697                     var typeParameter = typeParameters[i] = createTypeParameter();
45698                     if (i < maxLength) {
45699                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45700                         property.type = typeParameter;
45701                         properties.push(property);
45702                     }
45703                 }
45704             }
45705             var literalTypes = [];
45706             for (var i = minLength; i <= maxLength; i++)
45707                 literalTypes.push(getLiteralType(i));
45708             var lengthSymbol = createSymbol(4 /* Property */, "length");
45709             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45710             properties.push(lengthSymbol);
45711             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45712             type.typeParameters = typeParameters;
45713             type.outerTypeParameters = undefined;
45714             type.localTypeParameters = typeParameters;
45715             type.instantiations = ts.createMap();
45716             type.instantiations.set(getTypeListId(type.typeParameters), type);
45717             type.target = type;
45718             type.resolvedTypeArguments = type.typeParameters;
45719             type.thisType = createTypeParameter();
45720             type.thisType.isThisType = true;
45721             type.thisType.constraint = type;
45722             type.declaredProperties = properties;
45723             type.declaredCallSignatures = ts.emptyArray;
45724             type.declaredConstructSignatures = ts.emptyArray;
45725             type.declaredStringIndexInfo = undefined;
45726             type.declaredNumberIndexInfo = undefined;
45727             type.minLength = minLength;
45728             type.hasRestElement = hasRestElement;
45729             type.readonly = readonly;
45730             type.associatedNames = associatedNames;
45731             return type;
45732         }
45733         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45734             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45735             var type = tupleTypes.get(key);
45736             if (!type) {
45737                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45738             }
45739             return type;
45740         }
45741         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45742             if (minLength === void 0) { minLength = elementTypes.length; }
45743             if (hasRestElement === void 0) { hasRestElement = false; }
45744             if (readonly === void 0) { readonly = false; }
45745             var arity = elementTypes.length;
45746             if (arity === 1 && hasRestElement) {
45747                 return createArrayType(elementTypes[0], readonly);
45748             }
45749             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45750             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45751         }
45752         function sliceTupleType(type, index) {
45753             var tuple = type.target;
45754             if (tuple.hasRestElement) {
45755                 // don't slice off rest element
45756                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45757             }
45758             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45759         }
45760         function getTypeFromOptionalTypeNode(node) {
45761             var type = getTypeFromTypeNode(node.type);
45762             return strictNullChecks ? getOptionalType(type) : type;
45763         }
45764         function getTypeId(type) {
45765             return type.id;
45766         }
45767         function containsType(types, type) {
45768             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45769         }
45770         function insertType(types, type) {
45771             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45772             if (index < 0) {
45773                 types.splice(~index, 0, type);
45774                 return true;
45775             }
45776             return false;
45777         }
45778         function addTypeToUnion(typeSet, includes, type) {
45779             var flags = type.flags;
45780             if (flags & 1048576 /* Union */) {
45781                 return addTypesToUnion(typeSet, includes, type.types);
45782             }
45783             // We ignore 'never' types in unions
45784             if (!(flags & 131072 /* Never */)) {
45785                 includes |= flags & 71041023 /* IncludesMask */;
45786                 if (flags & 66846720 /* StructuredOrInstantiable */)
45787                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45788                 if (type === wildcardType)
45789                     includes |= 8388608 /* IncludesWildcard */;
45790                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45791                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45792                         includes |= 4194304 /* IncludesNonWideningType */;
45793                 }
45794                 else {
45795                     var len = typeSet.length;
45796                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45797                     if (index < 0) {
45798                         typeSet.splice(~index, 0, type);
45799                     }
45800                 }
45801             }
45802             return includes;
45803         }
45804         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45805         // and nested types of the given kind are flattened into the set.
45806         function addTypesToUnion(typeSet, includes, types) {
45807             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45808                 var type = types_9[_i];
45809                 includes = addTypeToUnion(typeSet, includes, type);
45810             }
45811             return includes;
45812         }
45813         function isSetOfLiteralsFromSameEnum(types) {
45814             var first = types[0];
45815             if (first.flags & 1024 /* EnumLiteral */) {
45816                 var firstEnum = getParentOfSymbol(first.symbol);
45817                 for (var i = 1; i < types.length; i++) {
45818                     var other = types[i];
45819                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45820                         return false;
45821                     }
45822                 }
45823                 return true;
45824             }
45825             return false;
45826         }
45827         function removeSubtypes(types, primitivesOnly) {
45828             var len = types.length;
45829             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
45830                 return true;
45831             }
45832             var i = len;
45833             var count = 0;
45834             while (i > 0) {
45835                 i--;
45836                 var source = types[i];
45837                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
45838                     var target = types_10[_i];
45839                     if (source !== target) {
45840                         if (count === 100000) {
45841                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
45842                             // same ratio of checks per element. If the estimated number of remaining type checks is
45843                             // greater than an upper limit we deem the union type too complex to represent. The
45844                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
45845                             // caps union types at 5000 unique literal types and 1000 unique object types.
45846                             var estimatedCount = (count / (len - i)) * len;
45847                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
45848                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
45849                                 return false;
45850                             }
45851                         }
45852                         count++;
45853                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
45854                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
45855                             isTypeDerivedFrom(source, target))) {
45856                             ts.orderedRemoveItemAt(types, i);
45857                             break;
45858                         }
45859                     }
45860                 }
45861             }
45862             return true;
45863         }
45864         function removeRedundantLiteralTypes(types, includes) {
45865             var i = types.length;
45866             while (i > 0) {
45867                 i--;
45868                 var t = types[i];
45869                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
45870                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
45871                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
45872                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
45873                     isFreshLiteralType(t) && containsType(types, t.regularType);
45874                 if (remove) {
45875                     ts.orderedRemoveItemAt(types, i);
45876                 }
45877             }
45878         }
45879         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
45880         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
45881         // of other types. Subtype reduction is expensive for large union types and is possible only when union
45882         // types are known not to circularly reference themselves (as is the case with union types created by
45883         // expression constructs such as array literals and the || and ?: operators). Named types can
45884         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
45885         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
45886         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
45887             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
45888             if (types.length === 0) {
45889                 return neverType;
45890             }
45891             if (types.length === 1) {
45892                 return types[0];
45893             }
45894             var typeSet = [];
45895             var includes = addTypesToUnion(typeSet, 0, types);
45896             if (unionReduction !== 0 /* None */) {
45897                 if (includes & 3 /* AnyOrUnknown */) {
45898                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
45899                 }
45900                 switch (unionReduction) {
45901                     case 1 /* Literal */:
45902                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
45903                             removeRedundantLiteralTypes(typeSet, includes);
45904                         }
45905                         break;
45906                     case 2 /* Subtype */:
45907                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
45908                             return errorType;
45909                         }
45910                         break;
45911                 }
45912                 if (typeSet.length === 0) {
45913                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
45914                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
45915                             neverType;
45916                 }
45917             }
45918             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
45919                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
45920             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
45921         }
45922         function getUnionTypePredicate(signatures) {
45923             var first;
45924             var types = [];
45925             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
45926                 var sig = signatures_6[_i];
45927                 var pred = getTypePredicateOfSignature(sig);
45928                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
45929                     continue;
45930                 }
45931                 if (first) {
45932                     if (!typePredicateKindsMatch(first, pred)) {
45933                         // No common type predicate.
45934                         return undefined;
45935                     }
45936                 }
45937                 else {
45938                     first = pred;
45939                 }
45940                 types.push(pred.type);
45941             }
45942             if (!first) {
45943                 // No union signatures had a type predicate.
45944                 return undefined;
45945             }
45946             var unionType = getUnionType(types);
45947             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
45948         }
45949         function typePredicateKindsMatch(a, b) {
45950             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
45951         }
45952         // This function assumes the constituent type list is sorted and deduplicated.
45953         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
45954             if (types.length === 0) {
45955                 return neverType;
45956             }
45957             if (types.length === 1) {
45958                 return types[0];
45959             }
45960             var id = getTypeListId(types);
45961             var type = unionTypes.get(id);
45962             if (!type) {
45963                 type = createType(1048576 /* Union */);
45964                 unionTypes.set(id, type);
45965                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
45966                 type.types = types;
45967                 /*
45968                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
45969                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
45970                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
45971                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
45972                 */
45973                 type.aliasSymbol = aliasSymbol;
45974                 type.aliasTypeArguments = aliasTypeArguments;
45975             }
45976             return type;
45977         }
45978         function getTypeFromUnionTypeNode(node) {
45979             var links = getNodeLinks(node);
45980             if (!links.resolvedType) {
45981                 var aliasSymbol = getAliasSymbolForTypeNode(node);
45982                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
45983             }
45984             return links.resolvedType;
45985         }
45986         function addTypeToIntersection(typeSet, includes, type) {
45987             var flags = type.flags;
45988             if (flags & 2097152 /* Intersection */) {
45989                 return addTypesToIntersection(typeSet, includes, type.types);
45990             }
45991             if (isEmptyAnonymousObjectType(type)) {
45992                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
45993                     includes |= 16777216 /* IncludesEmptyObject */;
45994                     typeSet.set(type.id.toString(), type);
45995                 }
45996             }
45997             else {
45998                 if (flags & 3 /* AnyOrUnknown */) {
45999                     if (type === wildcardType)
46000                         includes |= 8388608 /* IncludesWildcard */;
46001                 }
46002                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46003                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46004                         // We have seen two distinct unit types which means we should reduce to an
46005                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46006                         includes |= 67108864 /* NonPrimitive */;
46007                     }
46008                     typeSet.set(type.id.toString(), type);
46009                 }
46010                 includes |= flags & 71041023 /* IncludesMask */;
46011             }
46012             return includes;
46013         }
46014         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46015         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46016         function addTypesToIntersection(typeSet, includes, types) {
46017             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46018                 var type = types_11[_i];
46019                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46020             }
46021             return includes;
46022         }
46023         function removeRedundantPrimitiveTypes(types, includes) {
46024             var i = types.length;
46025             while (i > 0) {
46026                 i--;
46027                 var t = types[i];
46028                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46029                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46030                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46031                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46032                 if (remove) {
46033                     ts.orderedRemoveItemAt(types, i);
46034                 }
46035             }
46036         }
46037         // Check that the given type has a match in every union. A given type is matched by
46038         // an identical type, and a literal type is additionally matched by its corresponding
46039         // primitive type.
46040         function eachUnionContains(unionTypes, type) {
46041             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46042                 var u = unionTypes_1[_i];
46043                 if (!containsType(u.types, type)) {
46044                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46045                         type.flags & 256 /* NumberLiteral */ ? numberType :
46046                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46047                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46048                                     undefined;
46049                     if (!primitive || !containsType(u.types, primitive)) {
46050                         return false;
46051                     }
46052                 }
46053             }
46054             return true;
46055         }
46056         function extractIrreducible(types, flag) {
46057             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46058                 for (var i = 0; i < types.length; i++) {
46059                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46060                 }
46061                 return true;
46062             }
46063             return false;
46064         }
46065         // If the given list of types contains more than one union of primitive types, replace the
46066         // first with a union containing an intersection of those primitive types, then remove the
46067         // other unions and return true. Otherwise, do nothing and return false.
46068         function intersectUnionsOfPrimitiveTypes(types) {
46069             var unionTypes;
46070             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46071             if (index < 0) {
46072                 return false;
46073             }
46074             var i = index + 1;
46075             // Remove all but the first union of primitive types and collect them in
46076             // the unionTypes array.
46077             while (i < types.length) {
46078                 var t = types[i];
46079                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46080                     (unionTypes || (unionTypes = [types[index]])).push(t);
46081                     ts.orderedRemoveItemAt(types, i);
46082                 }
46083                 else {
46084                     i++;
46085                 }
46086             }
46087             // Return false if there was only one union of primitive types
46088             if (!unionTypes) {
46089                 return false;
46090             }
46091             // We have more than one union of primitive types, now intersect them. For each
46092             // type in each union we check if the type is matched in every union and if so
46093             // we include it in the result.
46094             var checked = [];
46095             var result = [];
46096             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46097                 var u = unionTypes_2[_i];
46098                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46099                     var t = _b[_a];
46100                     if (insertType(checked, t)) {
46101                         if (eachUnionContains(unionTypes, t)) {
46102                             insertType(result, t);
46103                         }
46104                     }
46105                 }
46106             }
46107             // Finally replace the first union with the result
46108             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46109             return true;
46110         }
46111         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46112             var result = createType(2097152 /* Intersection */);
46113             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46114             result.types = types;
46115             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46116             result.aliasTypeArguments = aliasTypeArguments;
46117             return result;
46118         }
46119         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46120         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46121         // types with union type constituents into equivalent union types with intersection type constituents and
46122         // effectively ensure that union types are always at the top level in type representations.
46123         //
46124         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46125         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46126         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46127         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46128         // for intersections of types with signatures can be deterministic.
46129         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46130             var typeMembershipMap = ts.createMap();
46131             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46132             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46133             // An intersection type is considered empty if it contains
46134             // the type never, or
46135             // more than one unit type or,
46136             // an object type and a nullable type (null or undefined), or
46137             // a string-like type and a type known to be non-string-like, or
46138             // a number-like type and a type known to be non-number-like, or
46139             // a symbol-like type and a type known to be non-symbol-like, or
46140             // a void-like type and a type known to be non-void-like, or
46141             // a non-primitive type and a type known to be primitive.
46142             if (includes & 131072 /* Never */ ||
46143                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46144                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46145                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46146                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46147                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46148                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46149                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46150                 return neverType;
46151             }
46152             if (includes & 1 /* Any */) {
46153                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46154             }
46155             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46156                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46157             }
46158             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46159                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46160                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46161                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46162                 removeRedundantPrimitiveTypes(typeSet, includes);
46163             }
46164             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46165                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46166             }
46167             if (typeSet.length === 0) {
46168                 return unknownType;
46169             }
46170             if (typeSet.length === 1) {
46171                 return typeSet[0];
46172             }
46173             var id = getTypeListId(typeSet);
46174             var result = intersectionTypes.get(id);
46175             if (!result) {
46176                 if (includes & 1048576 /* Union */) {
46177                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46178                         // When the intersection creates a reduced set (which might mean that *all* union types have
46179                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46180                         // reduced we'll never reduce again, so this occurs at most once.
46181                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46182                     }
46183                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46184                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46185                     }
46186                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46187                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46188                     }
46189                     else {
46190                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46191                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46192                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46193                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46194                         if (size >= 100000) {
46195                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46196                             return errorType;
46197                         }
46198                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46199                         var unionType = typeSet[unionIndex_1];
46200                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46201                     }
46202                 }
46203                 else {
46204                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46205                 }
46206                 intersectionTypes.set(id, result);
46207             }
46208             return result;
46209         }
46210         function getTypeFromIntersectionTypeNode(node) {
46211             var links = getNodeLinks(node);
46212             if (!links.resolvedType) {
46213                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46214                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46215             }
46216             return links.resolvedType;
46217         }
46218         function createIndexType(type, stringsOnly) {
46219             var result = createType(4194304 /* Index */);
46220             result.type = type;
46221             result.stringsOnly = stringsOnly;
46222             return result;
46223         }
46224         function getIndexTypeForGenericType(type, stringsOnly) {
46225             return stringsOnly ?
46226                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46227                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46228         }
46229         function getLiteralTypeFromPropertyName(name) {
46230             if (ts.isPrivateIdentifier(name)) {
46231                 return neverType;
46232             }
46233             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46234                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46235         }
46236         function getBigIntLiteralType(node) {
46237             return getLiteralType({
46238                 negative: false,
46239                 base10Value: ts.parsePseudoBigInt(node.text)
46240             });
46241         }
46242         function getLiteralTypeFromProperty(prop, include) {
46243             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46244                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46245                 if (!type && !ts.isKnownSymbol(prop)) {
46246                     if (prop.escapedName === "default" /* Default */) {
46247                         type = getLiteralType("default");
46248                     }
46249                     else {
46250                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46251                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46252                     }
46253                 }
46254                 if (type && type.flags & include) {
46255                     return type;
46256                 }
46257             }
46258             return neverType;
46259         }
46260         function getLiteralTypeFromProperties(type, include) {
46261             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46262         }
46263         function getNonEnumNumberIndexInfo(type) {
46264             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46265             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46266         }
46267         function getIndexType(type, stringsOnly, noIndexSignatures) {
46268             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46269             type = getReducedType(type);
46270             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46271                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46272                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46273                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46274                             type === wildcardType ? wildcardType :
46275                                 type.flags & 2 /* Unknown */ ? neverType :
46276                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46277                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46278                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46279                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46280                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46281         }
46282         function getExtractStringType(type) {
46283             if (keyofStringsOnly) {
46284                 return type;
46285             }
46286             var extractTypeAlias = getGlobalExtractSymbol();
46287             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46288         }
46289         function getIndexTypeOrString(type) {
46290             var indexType = getExtractStringType(getIndexType(type));
46291             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46292         }
46293         function getTypeFromTypeOperatorNode(node) {
46294             var links = getNodeLinks(node);
46295             if (!links.resolvedType) {
46296                 switch (node.operator) {
46297                     case 134 /* KeyOfKeyword */:
46298                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46299                         break;
46300                     case 147 /* UniqueKeyword */:
46301                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46302                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46303                             : errorType;
46304                         break;
46305                     case 138 /* ReadonlyKeyword */:
46306                         links.resolvedType = getTypeFromTypeNode(node.type);
46307                         break;
46308                     default:
46309                         throw ts.Debug.assertNever(node.operator);
46310                 }
46311             }
46312             return links.resolvedType;
46313         }
46314         function createIndexedAccessType(objectType, indexType) {
46315             var type = createType(8388608 /* IndexedAccess */);
46316             type.objectType = objectType;
46317             type.indexType = indexType;
46318             return type;
46319         }
46320         /**
46321          * Returns if a type is or consists of a JSLiteral object type
46322          * In addition to objects which are directly literals,
46323          * * unions where every element is a jsliteral
46324          * * intersections where at least one element is a jsliteral
46325          * * and instantiable types constrained to a jsliteral
46326          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46327          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46328          */
46329         function isJSLiteralType(type) {
46330             if (noImplicitAny) {
46331                 return false; // Flag is meaningless under `noImplicitAny` mode
46332             }
46333             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46334                 return true;
46335             }
46336             if (type.flags & 1048576 /* Union */) {
46337                 return ts.every(type.types, isJSLiteralType);
46338             }
46339             if (type.flags & 2097152 /* Intersection */) {
46340                 return ts.some(type.types, isJSLiteralType);
46341             }
46342             if (type.flags & 63176704 /* Instantiable */) {
46343                 return isJSLiteralType(getResolvedBaseConstraint(type));
46344             }
46345             return false;
46346         }
46347         function getPropertyNameFromIndex(indexType, accessNode) {
46348             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46349             return isTypeUsableAsPropertyName(indexType) ?
46350                 getPropertyNameFromType(indexType) :
46351                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46352                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46353                     accessNode && ts.isPropertyName(accessNode) ?
46354                         // late bound names are handled in the first branch, so here we only need to handle normal names
46355                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46356                         undefined;
46357         }
46358         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46359             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46360             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46361             if (propName !== undefined) {
46362                 var prop = getPropertyOfType(objectType, propName);
46363                 if (prop) {
46364                     if (accessExpression) {
46365                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46366                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46367                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46368                             return undefined;
46369                         }
46370                         if (accessFlags & 4 /* CacheSymbol */) {
46371                             getNodeLinks(accessNode).resolvedSymbol = prop;
46372                         }
46373                     }
46374                     var propType = getTypeOfSymbol(prop);
46375                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46376                         getFlowTypeOfReference(accessExpression, propType) :
46377                         propType;
46378                 }
46379                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46380                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46381                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46382                         if (isTupleType(objectType)) {
46383                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46384                         }
46385                         else {
46386                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46387                         }
46388                     }
46389                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46390                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46391                 }
46392             }
46393             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46394                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46395                     return objectType;
46396                 }
46397                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46398                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46399                 if (indexInfo) {
46400                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46401                         if (accessExpression) {
46402                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46403                         }
46404                         return undefined;
46405                     }
46406                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46407                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46408                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46409                         return indexInfo.type;
46410                     }
46411                     errorIfWritingToReadonlyIndex(indexInfo);
46412                     return indexInfo.type;
46413                 }
46414                 if (indexType.flags & 131072 /* Never */) {
46415                     return neverType;
46416                 }
46417                 if (isJSLiteralType(objectType)) {
46418                     return anyType;
46419                 }
46420                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46421                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46422                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46423                     }
46424                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46425                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46426                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46427                         }
46428                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46429                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46430                         }
46431                         else {
46432                             var suggestion = void 0;
46433                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46434                                 if (suggestion !== undefined) {
46435                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46436                                 }
46437                             }
46438                             else {
46439                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46440                                 if (suggestion_1 !== undefined) {
46441                                     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);
46442                                 }
46443                                 else {
46444                                     var errorInfo = void 0;
46445                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46446                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46447                                     }
46448                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46449                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46450                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46451                                     }
46452                                     else if (indexType.flags & 128 /* StringLiteral */) {
46453                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46454                                     }
46455                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46456                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46457                                     }
46458                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46459                                         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));
46460                                     }
46461                                     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));
46462                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46463                                 }
46464                             }
46465                         }
46466                     }
46467                     return undefined;
46468                 }
46469             }
46470             if (isJSLiteralType(objectType)) {
46471                 return anyType;
46472             }
46473             if (accessNode) {
46474                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46475                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46476                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46477                 }
46478                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46479                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46480                 }
46481                 else {
46482                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46483                 }
46484             }
46485             if (isTypeAny(indexType)) {
46486                 return indexType;
46487             }
46488             return undefined;
46489             function errorIfWritingToReadonlyIndex(indexInfo) {
46490                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46491                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46492                 }
46493             }
46494         }
46495         function getIndexNodeForAccessExpression(accessNode) {
46496             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46497                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46498                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46499                         accessNode;
46500         }
46501         function isGenericObjectType(type) {
46502             if (type.flags & 3145728 /* UnionOrIntersection */) {
46503                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46504                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46505                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46506                 }
46507                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46508             }
46509             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46510         }
46511         function isGenericIndexType(type) {
46512             if (type.flags & 3145728 /* UnionOrIntersection */) {
46513                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46514                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46515                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46516                 }
46517                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46518             }
46519             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46520         }
46521         function isThisTypeParameter(type) {
46522             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46523         }
46524         function getSimplifiedType(type, writing) {
46525             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46526                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46527                     type;
46528         }
46529         function distributeIndexOverObjectType(objectType, indexType, writing) {
46530             // (T | U)[K] -> T[K] | U[K] (reading)
46531             // (T | U)[K] -> T[K] & U[K] (writing)
46532             // (T & U)[K] -> T[K] & U[K]
46533             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46534                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46535                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46536             }
46537         }
46538         function distributeObjectOverIndexType(objectType, indexType, writing) {
46539             // T[A | B] -> T[A] | T[B] (reading)
46540             // T[A | B] -> T[A] & T[B] (writing)
46541             if (indexType.flags & 1048576 /* Union */) {
46542                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46543                 return writing ? getIntersectionType(types) : getUnionType(types);
46544             }
46545         }
46546         function unwrapSubstitution(type) {
46547             if (type.flags & 33554432 /* Substitution */) {
46548                 return type.substitute;
46549             }
46550             return type;
46551         }
46552         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46553         // the type itself if no transformation is possible. The writing flag indicates that the type is
46554         // the target of an assignment.
46555         function getSimplifiedIndexedAccessType(type, writing) {
46556             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46557             if (type[cache]) {
46558                 return type[cache] === circularConstraintType ? type : type[cache];
46559             }
46560             type[cache] = circularConstraintType;
46561             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46562             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46563             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46564             var indexType = getSimplifiedType(type.indexType, writing);
46565             // T[A | B] -> T[A] | T[B] (reading)
46566             // T[A | B] -> T[A] & T[B] (writing)
46567             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46568             if (distributedOverIndex) {
46569                 return type[cache] = distributedOverIndex;
46570             }
46571             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46572             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46573                 // (T | U)[K] -> T[K] | U[K] (reading)
46574                 // (T | U)[K] -> T[K] & U[K] (writing)
46575                 // (T & U)[K] -> T[K] & U[K]
46576                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46577                 if (distributedOverObject) {
46578                     return type[cache] = distributedOverObject;
46579                 }
46580             }
46581             // So ultimately (reading):
46582             // ((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]
46583             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46584             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46585             // construct the type Box<T[X]>.
46586             if (isGenericMappedType(objectType)) {
46587                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46588             }
46589             return type[cache] = type;
46590         }
46591         function getSimplifiedConditionalType(type, writing) {
46592             var checkType = type.checkType;
46593             var extendsType = type.extendsType;
46594             var trueType = getTrueTypeFromConditionalType(type);
46595             var falseType = getFalseTypeFromConditionalType(type);
46596             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46597             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46598                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46599                     return getSimplifiedType(trueType, writing);
46600                 }
46601                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46602                     return neverType;
46603                 }
46604             }
46605             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46606                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46607                     return neverType;
46608                 }
46609                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46610                     return getSimplifiedType(falseType, writing);
46611                 }
46612             }
46613             return type;
46614         }
46615         /**
46616          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46617          */
46618         function isIntersectionEmpty(type1, type2) {
46619             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46620         }
46621         function substituteIndexedMappedType(objectType, index) {
46622             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46623             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46624             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46625         }
46626         function getIndexedAccessType(objectType, indexType, accessNode) {
46627             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */) || (accessNode ? errorType : unknownType);
46628         }
46629         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags) {
46630             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46631             if (objectType === wildcardType || indexType === wildcardType) {
46632                 return wildcardType;
46633             }
46634             // If the object type has a string index signature and no other members we know that the result will
46635             // always be the type of that index signature and we can simplify accordingly.
46636             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46637                 indexType = stringType;
46638             }
46639             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46640             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46641             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46642             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46643             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46644             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46645                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46646                     return objectType;
46647                 }
46648                 // Defer the operation by creating an indexed access type.
46649                 var id = objectType.id + "," + indexType.id;
46650                 var type = indexedAccessTypes.get(id);
46651                 if (!type) {
46652                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType));
46653                 }
46654                 return type;
46655             }
46656             // In the following we resolve T[K] to the type of the property in T selected by K.
46657             // We treat boolean as different from other unions to improve errors;
46658             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46659             var apparentObjectType = getReducedApparentType(objectType);
46660             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46661                 var propTypes = [];
46662                 var wasMissingProp = false;
46663                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46664                     var t = _a[_i];
46665                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46666                     if (propType) {
46667                         propTypes.push(propType);
46668                     }
46669                     else if (!accessNode) {
46670                         // If there's no error node, we can immeditely stop, since error reporting is off
46671                         return undefined;
46672                     }
46673                     else {
46674                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46675                         wasMissingProp = true;
46676                     }
46677                 }
46678                 if (wasMissingProp) {
46679                     return undefined;
46680                 }
46681                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes) : getUnionType(propTypes);
46682             }
46683             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46684         }
46685         function getTypeFromIndexedAccessTypeNode(node) {
46686             var links = getNodeLinks(node);
46687             if (!links.resolvedType) {
46688                 var objectType = getTypeFromTypeNode(node.objectType);
46689                 var indexType = getTypeFromTypeNode(node.indexType);
46690                 var resolved = getIndexedAccessType(objectType, indexType, node);
46691                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46692                     resolved.objectType === objectType &&
46693                     resolved.indexType === indexType ?
46694                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46695             }
46696             return links.resolvedType;
46697         }
46698         function getTypeFromMappedTypeNode(node) {
46699             var links = getNodeLinks(node);
46700             if (!links.resolvedType) {
46701                 var type = createObjectType(32 /* Mapped */, node.symbol);
46702                 type.declaration = node;
46703                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46704                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46705                 links.resolvedType = type;
46706                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46707                 // references itself through one or more type aliases.
46708                 getConstraintTypeFromMappedType(type);
46709             }
46710             return links.resolvedType;
46711         }
46712         function getActualTypeVariable(type) {
46713             if (type.flags & 33554432 /* Substitution */) {
46714                 return type.baseType;
46715             }
46716             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46717                 type.indexType.flags & 33554432 /* Substitution */)) {
46718                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46719             }
46720             return type;
46721         }
46722         function getConditionalType(root, mapper) {
46723             var result;
46724             var extraTypes;
46725             var _loop_12 = function () {
46726                 var checkType = instantiateType(root.checkType, mapper);
46727                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46728                 var extendsType = instantiateType(root.extendsType, mapper);
46729                 if (checkType === wildcardType || extendsType === wildcardType) {
46730                     return { value: wildcardType };
46731                 }
46732                 var combinedMapper = void 0;
46733                 if (root.inferTypeParameters) {
46734                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46735                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46736                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46737                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46738                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46739                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46740                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46741                         // conditional type instead of deferring resolution. Also, we always want strict function
46742                         // types rules (i.e. proper contravariance) for inferences.
46743                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46744                     }
46745                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46746                 }
46747                 // Instantiate the extends type including inferences for 'infer T' type parameters
46748                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46749                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46750                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46751                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46752                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46753                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46754                     // then no instantiations will be and we can just return the false branch type.
46755                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46756                         // Return union of trueType and falseType for 'any' since it matches anything
46757                         if (checkType.flags & 1 /* Any */) {
46758                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46759                         }
46760                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46761                         // identical checkType, switch to that type and loop.
46762                         var falseType_1 = root.falseType;
46763                         if (falseType_1.flags & 16777216 /* Conditional */) {
46764                             var newRoot = falseType_1.root;
46765                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46766                                 root = newRoot;
46767                                 return "continue";
46768                             }
46769                         }
46770                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46771                         return "break";
46772                     }
46773                     // Return trueType for a definitely true extends check. We check instantiations of the two
46774                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46775                     // that has no constraint. This ensures that, for example, the type
46776                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46777                     // doesn't immediately resolve to 'string' instead of being deferred.
46778                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46779                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46780                         return "break";
46781                     }
46782                 }
46783                 // Return a deferred type for a check that is neither definitely true nor definitely false
46784                 var erasedCheckType = getActualTypeVariable(checkType);
46785                 result = createType(16777216 /* Conditional */);
46786                 result.root = root;
46787                 result.checkType = erasedCheckType;
46788                 result.extendsType = extendsType;
46789                 result.mapper = mapper;
46790                 result.combinedMapper = combinedMapper;
46791                 result.aliasSymbol = root.aliasSymbol;
46792                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46793                 return "break";
46794             };
46795             // We loop here for an immediately nested conditional type in the false position, effectively treating
46796             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46797             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46798             while (true) {
46799                 var state_4 = _loop_12();
46800                 if (typeof state_4 === "object")
46801                     return state_4.value;
46802                 if (state_4 === "break")
46803                     break;
46804             }
46805             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46806         }
46807         function getTrueTypeFromConditionalType(type) {
46808             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46809         }
46810         function getFalseTypeFromConditionalType(type) {
46811             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46812         }
46813         function getInferredTrueTypeFromConditionalType(type) {
46814             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46815         }
46816         function getInferTypeParameters(node) {
46817             var result;
46818             if (node.locals) {
46819                 node.locals.forEach(function (symbol) {
46820                     if (symbol.flags & 262144 /* TypeParameter */) {
46821                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
46822                     }
46823                 });
46824             }
46825             return result;
46826         }
46827         function getTypeFromConditionalTypeNode(node) {
46828             var links = getNodeLinks(node);
46829             if (!links.resolvedType) {
46830                 var checkType = getTypeFromTypeNode(node.checkType);
46831                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46832                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46833                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
46834                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
46835                 var root = {
46836                     node: node,
46837                     checkType: checkType,
46838                     extendsType: getTypeFromTypeNode(node.extendsType),
46839                     trueType: getTypeFromTypeNode(node.trueType),
46840                     falseType: getTypeFromTypeNode(node.falseType),
46841                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
46842                     inferTypeParameters: getInferTypeParameters(node),
46843                     outerTypeParameters: outerTypeParameters,
46844                     instantiations: undefined,
46845                     aliasSymbol: aliasSymbol,
46846                     aliasTypeArguments: aliasTypeArguments
46847                 };
46848                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
46849                 if (outerTypeParameters) {
46850                     root.instantiations = ts.createMap();
46851                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
46852                 }
46853             }
46854             return links.resolvedType;
46855         }
46856         function getTypeFromInferTypeNode(node) {
46857             var links = getNodeLinks(node);
46858             if (!links.resolvedType) {
46859                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
46860             }
46861             return links.resolvedType;
46862         }
46863         function getIdentifierChain(node) {
46864             if (ts.isIdentifier(node)) {
46865                 return [node];
46866             }
46867             else {
46868                 return ts.append(getIdentifierChain(node.left), node.right);
46869             }
46870         }
46871         function getTypeFromImportTypeNode(node) {
46872             var links = getNodeLinks(node);
46873             if (!links.resolvedType) {
46874                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
46875                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
46876                     links.resolvedSymbol = unknownSymbol;
46877                     return links.resolvedType = errorType;
46878                 }
46879                 if (!ts.isLiteralImportTypeNode(node)) {
46880                     error(node.argument, ts.Diagnostics.String_literal_expected);
46881                     links.resolvedSymbol = unknownSymbol;
46882                     return links.resolvedType = errorType;
46883                 }
46884                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
46885                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
46886                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
46887                 if (!innerModuleSymbol) {
46888                     links.resolvedSymbol = unknownSymbol;
46889                     return links.resolvedType = errorType;
46890                 }
46891                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
46892                 if (!ts.nodeIsMissing(node.qualifier)) {
46893                     var nameStack = getIdentifierChain(node.qualifier);
46894                     var currentNamespace = moduleSymbol;
46895                     var current = void 0;
46896                     while (current = nameStack.shift()) {
46897                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
46898                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
46899                         if (!next) {
46900                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
46901                             return links.resolvedType = errorType;
46902                         }
46903                         getNodeLinks(current).resolvedSymbol = next;
46904                         getNodeLinks(current.parent).resolvedSymbol = next;
46905                         currentNamespace = next;
46906                     }
46907                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
46908                 }
46909                 else {
46910                     if (moduleSymbol.flags & targetMeaning) {
46911                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
46912                     }
46913                     else {
46914                         var errorMessage = targetMeaning === 111551 /* Value */
46915                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
46916                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
46917                         error(node, errorMessage, node.argument.literal.text);
46918                         links.resolvedSymbol = unknownSymbol;
46919                         links.resolvedType = errorType;
46920                     }
46921                 }
46922             }
46923             return links.resolvedType;
46924         }
46925         function resolveImportSymbolType(node, links, symbol, meaning) {
46926             var resolvedSymbol = resolveSymbol(symbol);
46927             links.resolvedSymbol = resolvedSymbol;
46928             if (meaning === 111551 /* Value */) {
46929                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
46930             }
46931             else {
46932                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
46933             }
46934         }
46935         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
46936             var links = getNodeLinks(node);
46937             if (!links.resolvedType) {
46938                 // Deferred resolution of members is handled by resolveObjectTypeMembers
46939                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46940                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
46941                     links.resolvedType = emptyTypeLiteralType;
46942                 }
46943                 else {
46944                     var type = createObjectType(16 /* Anonymous */, node.symbol);
46945                     type.aliasSymbol = aliasSymbol;
46946                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46947                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
46948                         type = createArrayType(type);
46949                     }
46950                     links.resolvedType = type;
46951                 }
46952             }
46953             return links.resolvedType;
46954         }
46955         function getAliasSymbolForTypeNode(node) {
46956             var host = node.parent;
46957             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
46958                 host = host.parent;
46959             }
46960             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
46961         }
46962         function getTypeArgumentsForAliasSymbol(symbol) {
46963             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
46964         }
46965         function isNonGenericObjectType(type) {
46966             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
46967         }
46968         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
46969             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
46970         }
46971         function isSinglePropertyAnonymousObjectType(type) {
46972             return !!(type.flags & 524288 /* Object */) &&
46973                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
46974                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
46975         }
46976         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
46977             if (type.types.length === 2) {
46978                 var firstType = type.types[0];
46979                 var secondType = type.types[1];
46980                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
46981                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
46982                 }
46983                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
46984                     return getAnonymousPartialType(secondType);
46985                 }
46986                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
46987                     return getAnonymousPartialType(firstType);
46988                 }
46989             }
46990             function getAnonymousPartialType(type) {
46991                 // gets the type as if it had been spread, but where everything in the spread is made optional
46992                 var members = ts.createSymbolTable();
46993                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
46994                     var prop = _a[_i];
46995                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
46996                         // do nothing, skip privates
46997                     }
46998                     else if (isSpreadableProperty(prop)) {
46999                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47000                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47001                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47002                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47003                         result.declarations = prop.declarations;
47004                         result.nameType = getSymbolLinks(prop).nameType;
47005                         result.syntheticOrigin = prop;
47006                         members.set(prop.escapedName, result);
47007                     }
47008                 }
47009                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47010                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47011                 return spread;
47012             }
47013         }
47014         /**
47015          * Since the source of spread types are object literals, which are not binary,
47016          * this function should be called in a left folding style, with left = previous result of getSpreadType
47017          * and right = the new element to be spread.
47018          */
47019         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47020             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47021                 return anyType;
47022             }
47023             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47024                 return unknownType;
47025             }
47026             if (left.flags & 131072 /* Never */) {
47027                 return right;
47028             }
47029             if (right.flags & 131072 /* Never */) {
47030                 return left;
47031             }
47032             if (left.flags & 1048576 /* Union */) {
47033                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47034                 if (merged) {
47035                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47036                 }
47037                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47038             }
47039             if (right.flags & 1048576 /* Union */) {
47040                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47041                 if (merged) {
47042                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47043                 }
47044                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47045             }
47046             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47047                 return left;
47048             }
47049             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47050                 if (isEmptyObjectType(left)) {
47051                     return right;
47052                 }
47053                 // When the left type is an intersection, we may need to merge the last constituent of the
47054                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47055                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47056                 if (left.flags & 2097152 /* Intersection */) {
47057                     var types = left.types;
47058                     var lastLeft = types[types.length - 1];
47059                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47060                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47061                     }
47062                 }
47063                 return getIntersectionType([left, right]);
47064             }
47065             var members = ts.createSymbolTable();
47066             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47067             var stringIndexInfo;
47068             var numberIndexInfo;
47069             if (left === emptyObjectType) {
47070                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47071                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47072                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47073             }
47074             else {
47075                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47076                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47077             }
47078             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47079                 var rightProp = _a[_i];
47080                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47081                     skippedPrivateMembers.set(rightProp.escapedName, true);
47082                 }
47083                 else if (isSpreadableProperty(rightProp)) {
47084                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47085                 }
47086             }
47087             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47088                 var leftProp = _c[_b];
47089                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47090                     continue;
47091                 }
47092                 if (members.has(leftProp.escapedName)) {
47093                     var rightProp = members.get(leftProp.escapedName);
47094                     var rightType = getTypeOfSymbol(rightProp);
47095                     if (rightProp.flags & 16777216 /* Optional */) {
47096                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47097                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47098                         var result = createSymbol(flags, leftProp.escapedName);
47099                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47100                         result.leftSpread = leftProp;
47101                         result.rightSpread = rightProp;
47102                         result.declarations = declarations;
47103                         result.nameType = getSymbolLinks(leftProp).nameType;
47104                         members.set(leftProp.escapedName, result);
47105                     }
47106                 }
47107                 else {
47108                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47109                 }
47110             }
47111             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47112             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47113             return spread;
47114         }
47115         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47116         function isSpreadableProperty(prop) {
47117             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47118                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47119                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47120         }
47121         function getSpreadSymbol(prop, readonly) {
47122             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47123             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47124                 return prop;
47125             }
47126             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47127             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47128             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47129             result.declarations = prop.declarations;
47130             result.nameType = getSymbolLinks(prop).nameType;
47131             result.syntheticOrigin = prop;
47132             return result;
47133         }
47134         function getIndexInfoWithReadonly(info, readonly) {
47135             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47136         }
47137         function createLiteralType(flags, value, symbol) {
47138             var type = createType(flags);
47139             type.symbol = symbol;
47140             type.value = value;
47141             return type;
47142         }
47143         function getFreshTypeOfLiteralType(type) {
47144             if (type.flags & 2944 /* Literal */) {
47145                 if (!type.freshType) {
47146                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47147                     freshType.regularType = type;
47148                     freshType.freshType = freshType;
47149                     type.freshType = freshType;
47150                 }
47151                 return type.freshType;
47152             }
47153             return type;
47154         }
47155         function getRegularTypeOfLiteralType(type) {
47156             return type.flags & 2944 /* Literal */ ? type.regularType :
47157                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47158                     type;
47159         }
47160         function isFreshLiteralType(type) {
47161             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47162         }
47163         function getLiteralType(value, enumId, symbol) {
47164             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47165             // where NNN is the text representation of a numeric literal and SSS are the characters
47166             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47167             // EEE is a unique id for the containing enum type.
47168             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47169             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47170             var type = literalTypes.get(key);
47171             if (!type) {
47172                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47173                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47174                     (enumId ? 1024 /* EnumLiteral */ : 0);
47175                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47176                 type.regularType = type;
47177             }
47178             return type;
47179         }
47180         function getTypeFromLiteralTypeNode(node) {
47181             var links = getNodeLinks(node);
47182             if (!links.resolvedType) {
47183                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47184             }
47185             return links.resolvedType;
47186         }
47187         function createUniqueESSymbolType(symbol) {
47188             var type = createType(8192 /* UniqueESSymbol */);
47189             type.symbol = symbol;
47190             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47191             return type;
47192         }
47193         function getESSymbolLikeTypeForNode(node) {
47194             if (ts.isValidESSymbolDeclaration(node)) {
47195                 var symbol = getSymbolOfNode(node);
47196                 var links = getSymbolLinks(symbol);
47197                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47198             }
47199             return esSymbolType;
47200         }
47201         function getThisType(node) {
47202             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47203             var parent = container && container.parent;
47204             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47205                 if (!ts.hasModifier(container, 32 /* Static */) &&
47206                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47207                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47208                 }
47209             }
47210             // inside x.prototype = { ... }
47211             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47212                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47213             }
47214             // /** @return {this} */
47215             // x.prototype.m = function() { ... }
47216             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47217             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47218                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47219             }
47220             // inside constructor function C() { ... }
47221             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47222                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47223             }
47224             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47225             return errorType;
47226         }
47227         function getTypeFromThisTypeNode(node) {
47228             var links = getNodeLinks(node);
47229             if (!links.resolvedType) {
47230                 links.resolvedType = getThisType(node);
47231             }
47232             return links.resolvedType;
47233         }
47234         function getTypeFromTypeNode(node) {
47235             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47236         }
47237         function getTypeFromTypeNodeWorker(node) {
47238             switch (node.kind) {
47239                 case 125 /* AnyKeyword */:
47240                 case 295 /* JSDocAllType */:
47241                 case 296 /* JSDocUnknownType */:
47242                     return anyType;
47243                 case 148 /* UnknownKeyword */:
47244                     return unknownType;
47245                 case 143 /* StringKeyword */:
47246                     return stringType;
47247                 case 140 /* NumberKeyword */:
47248                     return numberType;
47249                 case 151 /* BigIntKeyword */:
47250                     return bigintType;
47251                 case 128 /* BooleanKeyword */:
47252                     return booleanType;
47253                 case 144 /* SymbolKeyword */:
47254                     return esSymbolType;
47255                 case 110 /* VoidKeyword */:
47256                     return voidType;
47257                 case 146 /* UndefinedKeyword */:
47258                     return undefinedType;
47259                 case 100 /* NullKeyword */:
47260                     return nullType;
47261                 case 137 /* NeverKeyword */:
47262                     return neverType;
47263                 case 141 /* ObjectKeyword */:
47264                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47265                 case 183 /* ThisType */:
47266                 case 104 /* ThisKeyword */:
47267                     return getTypeFromThisTypeNode(node);
47268                 case 187 /* LiteralType */:
47269                     return getTypeFromLiteralTypeNode(node);
47270                 case 169 /* TypeReference */:
47271                     return getTypeFromTypeReference(node);
47272                 case 168 /* TypePredicate */:
47273                     return node.assertsModifier ? voidType : booleanType;
47274                 case 216 /* ExpressionWithTypeArguments */:
47275                     return getTypeFromTypeReference(node);
47276                 case 172 /* TypeQuery */:
47277                     return getTypeFromTypeQueryNode(node);
47278                 case 174 /* ArrayType */:
47279                 case 175 /* TupleType */:
47280                     return getTypeFromArrayOrTupleTypeNode(node);
47281                 case 176 /* OptionalType */:
47282                     return getTypeFromOptionalTypeNode(node);
47283                 case 178 /* UnionType */:
47284                     return getTypeFromUnionTypeNode(node);
47285                 case 179 /* IntersectionType */:
47286                     return getTypeFromIntersectionTypeNode(node);
47287                 case 297 /* JSDocNullableType */:
47288                     return getTypeFromJSDocNullableTypeNode(node);
47289                 case 299 /* JSDocOptionalType */:
47290                     return addOptionality(getTypeFromTypeNode(node.type));
47291                 case 182 /* ParenthesizedType */:
47292                 case 298 /* JSDocNonNullableType */:
47293                 case 294 /* JSDocTypeExpression */:
47294                     return getTypeFromTypeNode(node.type);
47295                 case 177 /* RestType */:
47296                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47297                 case 301 /* JSDocVariadicType */:
47298                     return getTypeFromJSDocVariadicType(node);
47299                 case 170 /* FunctionType */:
47300                 case 171 /* ConstructorType */:
47301                 case 173 /* TypeLiteral */:
47302                 case 304 /* JSDocTypeLiteral */:
47303                 case 300 /* JSDocFunctionType */:
47304                 case 305 /* JSDocSignature */:
47305                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47306                 case 184 /* TypeOperator */:
47307                     return getTypeFromTypeOperatorNode(node);
47308                 case 185 /* IndexedAccessType */:
47309                     return getTypeFromIndexedAccessTypeNode(node);
47310                 case 186 /* MappedType */:
47311                     return getTypeFromMappedTypeNode(node);
47312                 case 180 /* ConditionalType */:
47313                     return getTypeFromConditionalTypeNode(node);
47314                 case 181 /* InferType */:
47315                     return getTypeFromInferTypeNode(node);
47316                 case 188 /* ImportType */:
47317                     return getTypeFromImportTypeNode(node);
47318                 // This function assumes that an identifier or qualified name is a type expression
47319                 // Callers should first ensure this by calling isTypeNode
47320                 case 75 /* Identifier */:
47321                 case 153 /* QualifiedName */:
47322                     var symbol = getSymbolAtLocation(node);
47323                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47324                 default:
47325                     return errorType;
47326             }
47327         }
47328         function instantiateList(items, mapper, instantiator) {
47329             if (items && items.length) {
47330                 for (var i = 0; i < items.length; i++) {
47331                     var item = items[i];
47332                     var mapped = instantiator(item, mapper);
47333                     if (item !== mapped) {
47334                         var result = i === 0 ? [] : items.slice(0, i);
47335                         result.push(mapped);
47336                         for (i++; i < items.length; i++) {
47337                             result.push(instantiator(items[i], mapper));
47338                         }
47339                         return result;
47340                     }
47341                 }
47342             }
47343             return items;
47344         }
47345         function instantiateTypes(types, mapper) {
47346             return instantiateList(types, mapper, instantiateType);
47347         }
47348         function instantiateSignatures(signatures, mapper) {
47349             return instantiateList(signatures, mapper, instantiateSignature);
47350         }
47351         function createTypeMapper(sources, targets) {
47352             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47353         }
47354         function getMappedType(type, mapper) {
47355             switch (mapper.kind) {
47356                 case 0 /* Simple */:
47357                     return type === mapper.source ? mapper.target : type;
47358                 case 1 /* Array */:
47359                     var sources = mapper.sources;
47360                     var targets = mapper.targets;
47361                     for (var i = 0; i < sources.length; i++) {
47362                         if (type === sources[i]) {
47363                             return targets ? targets[i] : anyType;
47364                         }
47365                     }
47366                     return type;
47367                 case 2 /* Function */:
47368                     return mapper.func(type);
47369                 case 3 /* Composite */:
47370                 case 4 /* Merged */:
47371                     var t1 = getMappedType(type, mapper.mapper1);
47372                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47373             }
47374         }
47375         function makeUnaryTypeMapper(source, target) {
47376             return { kind: 0 /* Simple */, source: source, target: target };
47377         }
47378         function makeArrayTypeMapper(sources, targets) {
47379             return { kind: 1 /* Array */, sources: sources, targets: targets };
47380         }
47381         function makeFunctionTypeMapper(func) {
47382             return { kind: 2 /* Function */, func: func };
47383         }
47384         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47385             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47386         }
47387         function createTypeEraser(sources) {
47388             return createTypeMapper(sources, /*targets*/ undefined);
47389         }
47390         /**
47391          * Maps forward-references to later types parameters to the empty object type.
47392          * This is used during inference when instantiating type parameter defaults.
47393          */
47394         function createBackreferenceMapper(context, index) {
47395             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47396         }
47397         function combineTypeMappers(mapper1, mapper2) {
47398             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47399         }
47400         function mergeTypeMappers(mapper1, mapper2) {
47401             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47402         }
47403         function prependTypeMapping(source, target, mapper) {
47404             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47405         }
47406         function appendTypeMapping(mapper, source, target) {
47407             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47408         }
47409         function getRestrictiveTypeParameter(tp) {
47410             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47411                 tp.restrictiveInstantiation.constraint = unknownType,
47412                 tp.restrictiveInstantiation);
47413         }
47414         function cloneTypeParameter(typeParameter) {
47415             var result = createTypeParameter(typeParameter.symbol);
47416             result.target = typeParameter;
47417             return result;
47418         }
47419         function instantiateTypePredicate(predicate, mapper) {
47420             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47421         }
47422         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47423             var freshTypeParameters;
47424             if (signature.typeParameters && !eraseTypeParameters) {
47425                 // First create a fresh set of type parameters, then include a mapping from the old to the
47426                 // new type parameters in the mapper function. Finally store this mapper in the new type
47427                 // parameters such that we can use it when instantiating constraints.
47428                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47429                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47430                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47431                     var tp = freshTypeParameters_1[_i];
47432                     tp.mapper = mapper;
47433                 }
47434             }
47435             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47436             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47437             // See GH#17600.
47438             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47439             /*resolvedReturnType*/ undefined, 
47440             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47441             result.target = signature;
47442             result.mapper = mapper;
47443             return result;
47444         }
47445         function instantiateSymbol(symbol, mapper) {
47446             var links = getSymbolLinks(symbol);
47447             if (links.type && !couldContainTypeVariables(links.type)) {
47448                 // If the type of the symbol is already resolved, and if that type could not possibly
47449                 // be affected by instantiation, simply return the symbol itself.
47450                 return symbol;
47451             }
47452             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47453                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47454                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47455                 // always reference a non-aliases.
47456                 symbol = links.target;
47457                 mapper = combineTypeMappers(links.mapper, mapper);
47458             }
47459             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47460             // also transient so that we can just store data on it directly.
47461             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47462             result.declarations = symbol.declarations;
47463             result.parent = symbol.parent;
47464             result.target = symbol;
47465             result.mapper = mapper;
47466             if (symbol.valueDeclaration) {
47467                 result.valueDeclaration = symbol.valueDeclaration;
47468             }
47469             if (links.nameType) {
47470                 result.nameType = links.nameType;
47471             }
47472             return result;
47473         }
47474         function getObjectTypeInstantiation(type, mapper) {
47475             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47476             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47477             var links = getNodeLinks(node);
47478             var typeParameters = links.outerTypeParameters;
47479             if (!typeParameters) {
47480                 // The first time an anonymous type is instantiated we compute and store a list of the type
47481                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47482                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47483                 // set of type parameters to those that are possibly referenced in the literal.
47484                 var declaration_1 = node;
47485                 if (ts.isInJSFile(declaration_1)) {
47486                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47487                     if (paramTag) {
47488                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47489                         if (paramSymbol) {
47490                             declaration_1 = paramSymbol.valueDeclaration;
47491                         }
47492                     }
47493                 }
47494                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47495                 if (isJSConstructor(declaration_1)) {
47496                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47497                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47498                 }
47499                 typeParameters = outerTypeParameters || ts.emptyArray;
47500                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47501                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47502                     typeParameters;
47503                 links.outerTypeParameters = typeParameters;
47504                 if (typeParameters.length) {
47505                     links.instantiations = ts.createMap();
47506                     links.instantiations.set(getTypeListId(typeParameters), target);
47507                 }
47508             }
47509             if (typeParameters.length) {
47510                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47511                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47512                 // instantiation cache key from the type IDs of the type arguments.
47513                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47514                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47515                 var id = getTypeListId(typeArguments);
47516                 var result = links.instantiations.get(id);
47517                 if (!result) {
47518                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47519                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47520                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47521                             instantiateAnonymousType(target, newMapper);
47522                     links.instantiations.set(id, result);
47523                 }
47524                 return result;
47525             }
47526             return type;
47527         }
47528         function maybeTypeParameterReference(node) {
47529             return !(node.kind === 153 /* QualifiedName */ ||
47530                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47531                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47532         }
47533         function isTypeParameterPossiblyReferenced(tp, node) {
47534             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47535             // between the node and the type parameter declaration, if the node contains actual references to the
47536             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47537             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47538                 var container = tp.symbol.declarations[0].parent;
47539                 for (var n = node; n !== container; n = n.parent) {
47540                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47541                         return true;
47542                     }
47543                 }
47544                 return !!ts.forEachChild(node, containsReference);
47545             }
47546             return true;
47547             function containsReference(node) {
47548                 switch (node.kind) {
47549                     case 183 /* ThisType */:
47550                         return !!tp.isThisType;
47551                     case 75 /* Identifier */:
47552                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47553                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47554                     case 172 /* TypeQuery */:
47555                         return true;
47556                 }
47557                 return !!ts.forEachChild(node, containsReference);
47558             }
47559         }
47560         function getHomomorphicTypeVariable(type) {
47561             var constraintType = getConstraintTypeFromMappedType(type);
47562             if (constraintType.flags & 4194304 /* Index */) {
47563                 var typeVariable = getActualTypeVariable(constraintType.type);
47564                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47565                     return typeVariable;
47566                 }
47567             }
47568             return undefined;
47569         }
47570         function instantiateMappedType(type, mapper) {
47571             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47572             // operation depends on T as follows:
47573             // * If T is a primitive type no mapping is performed and the result is simply T.
47574             // * If T is a union type we distribute the mapped type over the union.
47575             // * If T is an array we map to an array where the element type has been transformed.
47576             // * If T is a tuple we map to a tuple where the element types have been transformed.
47577             // * Otherwise we map to an object type where the type of each property has been transformed.
47578             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47579             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47580             // { [P in keyof A]: X } | undefined.
47581             var typeVariable = getHomomorphicTypeVariable(type);
47582             if (typeVariable) {
47583                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47584                 if (typeVariable !== mappedTypeVariable) {
47585                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47586                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47587                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47588                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47589                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47590                                     instantiateAnonymousType(type, replacementMapper);
47591                         }
47592                         return t;
47593                     });
47594                 }
47595             }
47596             return instantiateAnonymousType(type, mapper);
47597         }
47598         function getModifiedReadonlyState(state, modifiers) {
47599             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47600         }
47601         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47602             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47603             return elementType === errorType ? errorType :
47604                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47605         }
47606         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47607             var minLength = tupleType.target.minLength;
47608             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47609                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47610             });
47611             var modifiers = getMappedTypeModifiers(mappedType);
47612             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47613                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47614                     minLength;
47615             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47616             return ts.contains(elementTypes, errorType) ? errorType :
47617                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47618         }
47619         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47620             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47621             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47622             var modifiers = getMappedTypeModifiers(type);
47623             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47624                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47625                     propType;
47626         }
47627         function instantiateAnonymousType(type, mapper) {
47628             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47629             if (type.objectFlags & 32 /* Mapped */) {
47630                 result.declaration = type.declaration;
47631                 // C.f. instantiateSignature
47632                 var origTypeParameter = getTypeParameterFromMappedType(type);
47633                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47634                 result.typeParameter = freshTypeParameter;
47635                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47636                 freshTypeParameter.mapper = mapper;
47637             }
47638             result.target = type;
47639             result.mapper = mapper;
47640             result.aliasSymbol = type.aliasSymbol;
47641             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47642             return result;
47643         }
47644         function getConditionalTypeInstantiation(type, mapper) {
47645             var root = type.root;
47646             if (root.outerTypeParameters) {
47647                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47648                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47649                 // instantiation cache key from the type IDs of the type arguments.
47650                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47651                 var id = getTypeListId(typeArguments);
47652                 var result = root.instantiations.get(id);
47653                 if (!result) {
47654                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47655                     result = instantiateConditionalType(root, newMapper);
47656                     root.instantiations.set(id, result);
47657                 }
47658                 return result;
47659             }
47660             return type;
47661         }
47662         function instantiateConditionalType(root, mapper) {
47663             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47664             // the conditional type is distributive over union types and when T is instantiated to a union
47665             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47666             if (root.isDistributive) {
47667                 var checkType_1 = root.checkType;
47668                 var instantiatedType = getMappedType(checkType_1, mapper);
47669                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47670                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47671                 }
47672             }
47673             return getConditionalType(root, mapper);
47674         }
47675         function instantiateType(type, mapper) {
47676             if (!type || !mapper) {
47677                 return type;
47678             }
47679             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47680                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47681                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47682                 // the recursion here by yielding the error type.
47683                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47684                 return errorType;
47685             }
47686             totalInstantiationCount++;
47687             instantiationCount++;
47688             instantiationDepth++;
47689             var result = instantiateTypeWorker(type, mapper);
47690             instantiationDepth--;
47691             return result;
47692         }
47693         /**
47694          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47695          * simplification. It essentially removes the depth increase done in `instantiateType`.
47696          */
47697         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47698             instantiationDepth--;
47699             var result = instantiateType(type, mapper);
47700             instantiationDepth++;
47701             return result;
47702         }
47703         function instantiateTypeWorker(type, mapper) {
47704             var flags = type.flags;
47705             if (flags & 262144 /* TypeParameter */) {
47706                 return getMappedType(type, mapper);
47707             }
47708             if (flags & 524288 /* Object */) {
47709                 var objectFlags = type.objectFlags;
47710                 if (objectFlags & 16 /* Anonymous */) {
47711                     // If the anonymous type originates in a declaration of a function, method, class, or
47712                     // interface, in an object type literal, or in an object literal expression, we may need
47713                     // to instantiate the type because it might reference a type parameter.
47714                     return couldContainTypeVariables(type) ?
47715                         getObjectTypeInstantiation(type, mapper) : type;
47716                 }
47717                 if (objectFlags & 32 /* Mapped */) {
47718                     return getObjectTypeInstantiation(type, mapper);
47719                 }
47720                 if (objectFlags & 4 /* Reference */) {
47721                     if (type.node) {
47722                         return getObjectTypeInstantiation(type, mapper);
47723                     }
47724                     var resolvedTypeArguments = type.resolvedTypeArguments;
47725                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47726                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47727                 }
47728                 return type;
47729             }
47730             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47731                 if (!couldContainTypeVariables(type)) {
47732                     return type;
47733                 }
47734                 var types = type.types;
47735                 var newTypes = instantiateTypes(types, mapper);
47736                 return newTypes === types
47737                     ? type
47738                     : (flags & 2097152 /* Intersection */)
47739                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47740                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47741             }
47742             if (flags & 4194304 /* Index */) {
47743                 return getIndexType(instantiateType(type.type, mapper));
47744             }
47745             if (flags & 8388608 /* IndexedAccess */) {
47746                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper));
47747             }
47748             if (flags & 16777216 /* Conditional */) {
47749                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47750             }
47751             if (flags & 33554432 /* Substitution */) {
47752                 var maybeVariable = instantiateType(type.baseType, mapper);
47753                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47754                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47755                 }
47756                 else {
47757                     var sub = instantiateType(type.substitute, mapper);
47758                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47759                         return maybeVariable;
47760                     }
47761                     return sub;
47762                 }
47763             }
47764             return type;
47765         }
47766         function getPermissiveInstantiation(type) {
47767             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47768                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47769         }
47770         function getRestrictiveInstantiation(type) {
47771             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47772                 return type;
47773             }
47774             if (type.restrictiveInstantiation) {
47775                 return type.restrictiveInstantiation;
47776             }
47777             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47778             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47779             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47780             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47781             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47782             // are constrained to `unknown` and produce tons of false positives/negatives!
47783             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47784             return type.restrictiveInstantiation;
47785         }
47786         function instantiateIndexInfo(info, mapper) {
47787             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47788         }
47789         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47790         // that is subject to contextual typing.
47791         function isContextSensitive(node) {
47792             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47793             switch (node.kind) {
47794                 case 201 /* FunctionExpression */:
47795                 case 202 /* ArrowFunction */:
47796                 case 161 /* MethodDeclaration */:
47797                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47798                     return isContextSensitiveFunctionLikeDeclaration(node);
47799                 case 193 /* ObjectLiteralExpression */:
47800                     return ts.some(node.properties, isContextSensitive);
47801                 case 192 /* ArrayLiteralExpression */:
47802                     return ts.some(node.elements, isContextSensitive);
47803                 case 210 /* ConditionalExpression */:
47804                     return isContextSensitive(node.whenTrue) ||
47805                         isContextSensitive(node.whenFalse);
47806                 case 209 /* BinaryExpression */:
47807                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47808                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47809                 case 281 /* PropertyAssignment */:
47810                     return isContextSensitive(node.initializer);
47811                 case 200 /* ParenthesizedExpression */:
47812                     return isContextSensitive(node.expression);
47813                 case 274 /* JsxAttributes */:
47814                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47815                 case 273 /* JsxAttribute */: {
47816                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47817                     var initializer = node.initializer;
47818                     return !!initializer && isContextSensitive(initializer);
47819                 }
47820                 case 276 /* JsxExpression */: {
47821                     // It is possible to that node.expression is undefined (e.g <div x={} />)
47822                     var expression = node.expression;
47823                     return !!expression && isContextSensitive(expression);
47824                 }
47825             }
47826             return false;
47827         }
47828         function isContextSensitiveFunctionLikeDeclaration(node) {
47829             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
47830                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
47831         }
47832         function hasContextSensitiveParameters(node) {
47833             // Functions with type parameters are not context sensitive.
47834             if (!node.typeParameters) {
47835                 // Functions with any parameters that lack type annotations are context sensitive.
47836                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
47837                     return true;
47838                 }
47839                 if (node.kind !== 202 /* ArrowFunction */) {
47840                     // If the first parameter is not an explicit 'this' parameter, then the function has
47841                     // an implicit 'this' parameter which is subject to contextual typing.
47842                     var parameter = ts.firstOrUndefined(node.parameters);
47843                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
47844                         return true;
47845                     }
47846                 }
47847             }
47848             return false;
47849         }
47850         function hasContextSensitiveReturnExpression(node) {
47851             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
47852             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
47853         }
47854         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
47855             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
47856                 isContextSensitiveFunctionLikeDeclaration(func);
47857         }
47858         function getTypeWithoutSignatures(type) {
47859             if (type.flags & 524288 /* Object */) {
47860                 var resolved = resolveStructuredTypeMembers(type);
47861                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
47862                     var result = createObjectType(16 /* Anonymous */, type.symbol);
47863                     result.members = resolved.members;
47864                     result.properties = resolved.properties;
47865                     result.callSignatures = ts.emptyArray;
47866                     result.constructSignatures = ts.emptyArray;
47867                     return result;
47868                 }
47869             }
47870             else if (type.flags & 2097152 /* Intersection */) {
47871                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
47872             }
47873             return type;
47874         }
47875         // TYPE CHECKING
47876         function isTypeIdenticalTo(source, target) {
47877             return isTypeRelatedTo(source, target, identityRelation);
47878         }
47879         function compareTypesIdentical(source, target) {
47880             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
47881         }
47882         function compareTypesAssignable(source, target) {
47883             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
47884         }
47885         function compareTypesSubtypeOf(source, target) {
47886             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
47887         }
47888         function isTypeSubtypeOf(source, target) {
47889             return isTypeRelatedTo(source, target, subtypeRelation);
47890         }
47891         function isTypeAssignableTo(source, target) {
47892             return isTypeRelatedTo(source, target, assignableRelation);
47893         }
47894         // An object type S is considered to be derived from an object type T if
47895         // S is a union type and every constituent of S is derived from T,
47896         // T is a union type and S is derived from at least one constituent of T, or
47897         // S is a type variable with a base constraint that is derived from T,
47898         // T is one of the global types Object and Function and S is a subtype of T, or
47899         // T occurs directly or indirectly in an 'extends' clause of S.
47900         // Note that this check ignores type parameters and only considers the
47901         // inheritance hierarchy.
47902         function isTypeDerivedFrom(source, target) {
47903             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
47904                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
47905                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
47906                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
47907                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
47908                                 hasBaseType(source, getTargetType(target));
47909         }
47910         /**
47911          * This is *not* a bi-directional relationship.
47912          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
47913          *
47914          * 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.
47915          * It is used to check following cases:
47916          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
47917          *   - the types of `case` clause expressions and their respective `switch` expressions.
47918          *   - the type of an expression in a type assertion with the type being asserted.
47919          */
47920         function isTypeComparableTo(source, target) {
47921             return isTypeRelatedTo(source, target, comparableRelation);
47922         }
47923         function areTypesComparable(type1, type2) {
47924             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
47925         }
47926         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
47927             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
47928         }
47929         /**
47930          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
47931          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
47932          */
47933         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
47934             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
47935         }
47936         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
47937             if (isTypeRelatedTo(source, target, relation))
47938                 return true;
47939             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47940                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
47941             }
47942             return false;
47943         }
47944         function isOrHasGenericConditional(type) {
47945             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
47946         }
47947         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47948             if (!node || isOrHasGenericConditional(target))
47949                 return false;
47950             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
47951                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47952                 return true;
47953             }
47954             switch (node.kind) {
47955                 case 276 /* JsxExpression */:
47956                 case 200 /* ParenthesizedExpression */:
47957                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47958                 case 209 /* BinaryExpression */:
47959                     switch (node.operatorToken.kind) {
47960                         case 62 /* EqualsToken */:
47961                         case 27 /* CommaToken */:
47962                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47963                     }
47964                     break;
47965                 case 193 /* ObjectLiteralExpression */:
47966                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47967                 case 192 /* ArrayLiteralExpression */:
47968                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47969                 case 274 /* JsxAttributes */:
47970                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
47971                 case 202 /* ArrowFunction */:
47972                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
47973             }
47974             return false;
47975         }
47976         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47977             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
47978             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
47979             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
47980                 var signatures = _a[_i];
47981                 if (ts.some(signatures, function (s) {
47982                     var returnType = getReturnTypeOfSignature(s);
47983                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
47984                 })) {
47985                     var resultObj = errorOutputContainer || {};
47986                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
47987                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
47988                     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));
47989                     return true;
47990                 }
47991             }
47992             return false;
47993         }
47994         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
47995             // Don't elaborate blocks
47996             if (ts.isBlock(node.body)) {
47997                 return false;
47998             }
47999             // Or functions with annotated parameter types
48000             if (ts.some(node.parameters, ts.hasType)) {
48001                 return false;
48002             }
48003             var sourceSig = getSingleCallSignature(source);
48004             if (!sourceSig) {
48005                 return false;
48006             }
48007             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48008             if (!ts.length(targetSignatures)) {
48009                 return false;
48010             }
48011             var returnExpression = node.body;
48012             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48013             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48014             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48015                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48016                 if (elaborated) {
48017                     return elaborated;
48018                 }
48019                 var resultObj = errorOutputContainer || {};
48020                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48021                 if (resultObj.errors) {
48022                     if (target.symbol && ts.length(target.symbol.declarations)) {
48023                         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));
48024                     }
48025                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48026                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48027                         // an IPromise and a Promise that are slightly different
48028                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48029                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48030                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48031                     }
48032                     return true;
48033                 }
48034             }
48035             return false;
48036         }
48037         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48038             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48039             if (idx) {
48040                 return idx;
48041             }
48042             if (target.flags & 1048576 /* Union */) {
48043                 var best = getBestMatchingType(source, target);
48044                 if (best) {
48045                     return getIndexedAccessTypeOrUndefined(best, nameType);
48046                 }
48047             }
48048         }
48049         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48050             next.contextualType = sourcePropType;
48051             try {
48052                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48053             }
48054             finally {
48055                 next.contextualType = undefined;
48056             }
48057         }
48058         /**
48059          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48060          * 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`
48061          * Otherwise, we issue an error on _every_ element which fail the assignability check
48062          */
48063         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48064             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48065             var reportedError = false;
48066             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48067                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48068                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48069                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48070                     continue; // Don't elaborate on indexes on generic variables
48071                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48072                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48073                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48074                     if (elaborated) {
48075                         reportedError = true;
48076                     }
48077                     else {
48078                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48079                         var resultObj = errorOutputContainer || {};
48080                         // Use the expression type, if available
48081                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48082                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48083                         if (result && specificSource !== sourcePropType) {
48084                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48085                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48086                         }
48087                         if (resultObj.errors) {
48088                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48089                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48090                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48091                             var issuedElaboration = false;
48092                             if (!targetProp) {
48093                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48094                                     getIndexInfoOfType(target, 0 /* String */) ||
48095                                     undefined;
48096                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48097                                     issuedElaboration = true;
48098                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48099                                 }
48100                             }
48101                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48102                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48103                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48104                                     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)));
48105                                 }
48106                             }
48107                         }
48108                         reportedError = true;
48109                     }
48110                 }
48111             }
48112             return reportedError;
48113         }
48114         function generateJsxAttributes(node) {
48115             var _i, _a, prop;
48116             return __generator(this, function (_b) {
48117                 switch (_b.label) {
48118                     case 0:
48119                         if (!ts.length(node.properties))
48120                             return [2 /*return*/];
48121                         _i = 0, _a = node.properties;
48122                         _b.label = 1;
48123                     case 1:
48124                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48125                         prop = _a[_i];
48126                         if (ts.isJsxSpreadAttribute(prop))
48127                             return [3 /*break*/, 3];
48128                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48129                     case 2:
48130                         _b.sent();
48131                         _b.label = 3;
48132                     case 3:
48133                         _i++;
48134                         return [3 /*break*/, 1];
48135                     case 4: return [2 /*return*/];
48136                 }
48137             });
48138         }
48139         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48140             var memberOffset, i, child, nameType, elem;
48141             return __generator(this, function (_a) {
48142                 switch (_a.label) {
48143                     case 0:
48144                         if (!ts.length(node.children))
48145                             return [2 /*return*/];
48146                         memberOffset = 0;
48147                         i = 0;
48148                         _a.label = 1;
48149                     case 1:
48150                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48151                         child = node.children[i];
48152                         nameType = getLiteralType(i - memberOffset);
48153                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48154                         if (!elem) return [3 /*break*/, 3];
48155                         return [4 /*yield*/, elem];
48156                     case 2:
48157                         _a.sent();
48158                         return [3 /*break*/, 4];
48159                     case 3:
48160                         memberOffset++;
48161                         _a.label = 4;
48162                     case 4:
48163                         i++;
48164                         return [3 /*break*/, 1];
48165                     case 5: return [2 /*return*/];
48166                 }
48167             });
48168         }
48169         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48170             switch (child.kind) {
48171                 case 276 /* JsxExpression */:
48172                     // child is of the type of the expression
48173                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48174                 case 11 /* JsxText */:
48175                     if (child.containsOnlyTriviaWhiteSpaces) {
48176                         break; // Whitespace only jsx text isn't real jsx text
48177                     }
48178                     // child is a string
48179                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48180                 case 266 /* JsxElement */:
48181                 case 267 /* JsxSelfClosingElement */:
48182                 case 270 /* JsxFragment */:
48183                     // child is of type JSX.Element
48184                     return { errorNode: child, innerExpression: child, nameType: nameType };
48185                 default:
48186                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48187             }
48188         }
48189         function getSemanticJsxChildren(children) {
48190             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48191         }
48192         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48193             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48194             var invalidTextDiagnostic;
48195             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48196                 var containingElement = node.parent.parent;
48197                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48198                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48199                 var childrenNameType = getLiteralType(childrenPropName);
48200                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48201                 var validChildren = getSemanticJsxChildren(containingElement.children);
48202                 if (!ts.length(validChildren)) {
48203                     return result;
48204                 }
48205                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48206                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48207                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48208                 if (moreThanOneRealChildren) {
48209                     if (arrayLikeTargetParts !== neverType) {
48210                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48211                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48212                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48213                     }
48214                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48215                         // arity mismatch
48216                         result = true;
48217                         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));
48218                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48219                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48220                         }
48221                     }
48222                 }
48223                 else {
48224                     if (nonArrayLikeTargetParts !== neverType) {
48225                         var child = validChildren[0];
48226                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48227                         if (elem_1) {
48228                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48229                                 switch (_a.label) {
48230                                     case 0: return [4 /*yield*/, elem_1];
48231                                     case 1:
48232                                         _a.sent();
48233                                         return [2 /*return*/];
48234                                 }
48235                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48236                         }
48237                     }
48238                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48239                         // arity mismatch
48240                         result = true;
48241                         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));
48242                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48243                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48244                         }
48245                     }
48246                 }
48247             }
48248             return result;
48249             function getInvalidTextualChildDiagnostic() {
48250                 if (!invalidTextDiagnostic) {
48251                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48252                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48253                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48254                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48255                     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;
48256                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48257                 }
48258                 return invalidTextDiagnostic;
48259             }
48260         }
48261         function generateLimitedTupleElements(node, target) {
48262             var len, i, elem, nameType;
48263             return __generator(this, function (_a) {
48264                 switch (_a.label) {
48265                     case 0:
48266                         len = ts.length(node.elements);
48267                         if (!len)
48268                             return [2 /*return*/];
48269                         i = 0;
48270                         _a.label = 1;
48271                     case 1:
48272                         if (!(i < len)) return [3 /*break*/, 4];
48273                         // 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
48274                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48275                             return [3 /*break*/, 3];
48276                         elem = node.elements[i];
48277                         if (ts.isOmittedExpression(elem))
48278                             return [3 /*break*/, 3];
48279                         nameType = getLiteralType(i);
48280                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48281                     case 2:
48282                         _a.sent();
48283                         _a.label = 3;
48284                     case 3:
48285                         i++;
48286                         return [3 /*break*/, 1];
48287                     case 4: return [2 /*return*/];
48288                 }
48289             });
48290         }
48291         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48292             if (target.flags & 131068 /* Primitive */)
48293                 return false;
48294             if (isTupleLikeType(source)) {
48295                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48296             }
48297             // recreate a tuple from the elements, if possible
48298             // Since we're re-doing the expression type, we need to reapply the contextual type
48299             var oldContext = node.contextualType;
48300             node.contextualType = target;
48301             try {
48302                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48303                 node.contextualType = oldContext;
48304                 if (isTupleLikeType(tupleizedType)) {
48305                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48306                 }
48307                 return false;
48308             }
48309             finally {
48310                 node.contextualType = oldContext;
48311             }
48312         }
48313         function generateObjectLiteralElements(node) {
48314             var _i, _a, prop, type, _b;
48315             return __generator(this, function (_c) {
48316                 switch (_c.label) {
48317                     case 0:
48318                         if (!ts.length(node.properties))
48319                             return [2 /*return*/];
48320                         _i = 0, _a = node.properties;
48321                         _c.label = 1;
48322                     case 1:
48323                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48324                         prop = _a[_i];
48325                         if (ts.isSpreadAssignment(prop))
48326                             return [3 /*break*/, 7];
48327                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48328                         if (!type || (type.flags & 131072 /* Never */)) {
48329                             return [3 /*break*/, 7];
48330                         }
48331                         _b = prop.kind;
48332                         switch (_b) {
48333                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48334                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48335                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48336                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48337                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48338                         }
48339                         return [3 /*break*/, 6];
48340                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48341                     case 3:
48342                         _c.sent();
48343                         return [3 /*break*/, 7];
48344                     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 }];
48345                     case 5:
48346                         _c.sent();
48347                         return [3 /*break*/, 7];
48348                     case 6:
48349                         ts.Debug.assertNever(prop);
48350                         _c.label = 7;
48351                     case 7:
48352                         _i++;
48353                         return [3 /*break*/, 1];
48354                     case 8: return [2 /*return*/];
48355                 }
48356             });
48357         }
48358         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48359             if (target.flags & 131068 /* Primitive */)
48360                 return false;
48361             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48362         }
48363         /**
48364          * This is *not* a bi-directional relationship.
48365          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48366          */
48367         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48368             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48369         }
48370         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48371             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48372             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48373         }
48374         /**
48375          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48376          */
48377         function isAnySignature(s) {
48378             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48379                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48380                 isTypeAny(getReturnTypeOfSignature(s));
48381         }
48382         /**
48383          * See signatureRelatedTo, compareSignaturesIdentical
48384          */
48385         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48386             // TODO (drosen): De-duplicate code between related functions.
48387             if (source === target) {
48388                 return -1 /* True */;
48389             }
48390             if (isAnySignature(target)) {
48391                 return -1 /* True */;
48392             }
48393             var targetCount = getParameterCount(target);
48394             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48395                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48396             if (sourceHasMoreParameters) {
48397                 return 0 /* False */;
48398             }
48399             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48400                 target = getCanonicalSignature(target);
48401                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48402             }
48403             var sourceCount = getParameterCount(source);
48404             var sourceRestType = getNonArrayRestType(source);
48405             var targetRestType = getNonArrayRestType(target);
48406             if (sourceRestType || targetRestType) {
48407                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48408             }
48409             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48410                 // We're not able to relate misaligned complex rest parameters
48411                 return 0 /* False */;
48412             }
48413             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48414             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48415                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48416             var result = -1 /* True */;
48417             var sourceThisType = getThisTypeOfSignature(source);
48418             if (sourceThisType && sourceThisType !== voidType) {
48419                 var targetThisType = getThisTypeOfSignature(target);
48420                 if (targetThisType) {
48421                     // void sources are assignable to anything.
48422                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48423                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48424                     if (!related) {
48425                         if (reportErrors) {
48426                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48427                         }
48428                         return 0 /* False */;
48429                     }
48430                     result &= related;
48431                 }
48432             }
48433             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48434             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48435             for (var i = 0; i < paramCount; i++) {
48436                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48437                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48438                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48439                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48440                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48441                 // function types with a single call signature, we know we are relating two callback parameters. In
48442                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48443                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48444                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48445                 // with respect to T.
48446                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48447                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48448                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48449                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48450                 var related = callbacks ?
48451                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48452                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48453                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48454                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48455                     related = 0 /* False */;
48456                 }
48457                 if (!related) {
48458                     if (reportErrors) {
48459                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48460                     }
48461                     return 0 /* False */;
48462                 }
48463                 result &= related;
48464             }
48465             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48466                 // If a signature resolution is already in-flight, skip issuing a circularity error
48467                 // here and just use the `any` type directly
48468                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48469                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48470                         : getReturnTypeOfSignature(target);
48471                 if (targetReturnType === voidType) {
48472                     return result;
48473                 }
48474                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48475                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48476                         : getReturnTypeOfSignature(source);
48477                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48478                 var targetTypePredicate = getTypePredicateOfSignature(target);
48479                 if (targetTypePredicate) {
48480                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48481                     if (sourceTypePredicate) {
48482                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48483                     }
48484                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48485                         if (reportErrors) {
48486                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48487                         }
48488                         return 0 /* False */;
48489                     }
48490                 }
48491                 else {
48492                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48493                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48494                     // wouldn't be co-variant for T without this rule.
48495                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48496                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48497                     if (!result && reportErrors && incompatibleErrorReporter) {
48498                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48499                     }
48500                 }
48501             }
48502             return result;
48503         }
48504         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48505             if (source.kind !== target.kind) {
48506                 if (reportErrors) {
48507                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48508                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48509                 }
48510                 return 0 /* False */;
48511             }
48512             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48513                 if (source.parameterIndex !== target.parameterIndex) {
48514                     if (reportErrors) {
48515                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48516                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48517                     }
48518                     return 0 /* False */;
48519                 }
48520             }
48521             var related = source.type === target.type ? -1 /* True */ :
48522                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48523                     0 /* False */;
48524             if (related === 0 /* False */ && reportErrors) {
48525                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48526             }
48527             return related;
48528         }
48529         function isImplementationCompatibleWithOverload(implementation, overload) {
48530             var erasedSource = getErasedSignature(implementation);
48531             var erasedTarget = getErasedSignature(overload);
48532             // First see if the return types are compatible in either direction.
48533             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48534             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48535             if (targetReturnType === voidType
48536                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48537                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48538                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48539             }
48540             return false;
48541         }
48542         function isEmptyResolvedType(t) {
48543             return t !== anyFunctionType &&
48544                 t.properties.length === 0 &&
48545                 t.callSignatures.length === 0 &&
48546                 t.constructSignatures.length === 0 &&
48547                 !t.stringIndexInfo &&
48548                 !t.numberIndexInfo;
48549         }
48550         function isEmptyObjectType(type) {
48551             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48552                 type.flags & 67108864 /* NonPrimitive */ ? true :
48553                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48554                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48555                             false;
48556         }
48557         function isEmptyAnonymousObjectType(type) {
48558             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48559         }
48560         function isStringIndexSignatureOnlyType(type) {
48561             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48562                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48563                 false;
48564         }
48565         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48566             if (sourceSymbol === targetSymbol) {
48567                 return true;
48568             }
48569             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48570             var entry = enumRelation.get(id);
48571             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48572                 return !!(entry & 1 /* Succeeded */);
48573             }
48574             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48575                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48576                 return false;
48577             }
48578             var targetEnumType = getTypeOfSymbol(targetSymbol);
48579             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48580                 var property = _a[_i];
48581                 if (property.flags & 8 /* EnumMember */) {
48582                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48583                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48584                         if (errorReporter) {
48585                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48586                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48587                         }
48588                         else {
48589                             enumRelation.set(id, 2 /* Failed */);
48590                         }
48591                         return false;
48592                     }
48593                 }
48594             }
48595             enumRelation.set(id, 1 /* Succeeded */);
48596             return true;
48597         }
48598         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48599             var s = source.flags;
48600             var t = target.flags;
48601             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48602                 return true;
48603             if (t & 131072 /* Never */)
48604                 return false;
48605             if (s & 132 /* StringLike */ && t & 4 /* String */)
48606                 return true;
48607             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48608                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48609                 source.value === target.value)
48610                 return true;
48611             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48612                 return true;
48613             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48614                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48615                 source.value === target.value)
48616                 return true;
48617             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48618                 return true;
48619             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48620                 return true;
48621             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48622                 return true;
48623             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48624                 return true;
48625             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48626                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48627                     return true;
48628                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48629                     source.value === target.value &&
48630                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48631                     return true;
48632             }
48633             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48634                 return true;
48635             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48636                 return true;
48637             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48638                 return true;
48639             if (relation === assignableRelation || relation === comparableRelation) {
48640                 if (s & 1 /* Any */)
48641                     return true;
48642                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48643                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48644                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48645                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48646                     return true;
48647             }
48648             return false;
48649         }
48650         function isTypeRelatedTo(source, target, relation) {
48651             if (isFreshLiteralType(source)) {
48652                 source = source.regularType;
48653             }
48654             if (isFreshLiteralType(target)) {
48655                 target = target.regularType;
48656             }
48657             if (source === target) {
48658                 return true;
48659             }
48660             if (relation !== identityRelation) {
48661                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48662                     return true;
48663                 }
48664             }
48665             else {
48666                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48667                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48668                     return false;
48669             }
48670             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48671                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48672                 if (related !== undefined) {
48673                     return !!(related & 1 /* Succeeded */);
48674                 }
48675             }
48676             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48677                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48678             }
48679             return false;
48680         }
48681         function isIgnoredJsxProperty(source, sourceProp) {
48682             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48683         }
48684         function getNormalizedType(type, writing) {
48685             while (true) {
48686                 var t = isFreshLiteralType(type) ? type.regularType :
48687                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48688                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48689                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48690                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48691                                     type;
48692                 if (t === type)
48693                     break;
48694                 type = t;
48695             }
48696             return type;
48697         }
48698         /**
48699          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48700          * @param source The left-hand-side of the relation.
48701          * @param target The right-hand-side of the relation.
48702          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48703          * Used as both to determine which checks are performed and as a cache of previously computed results.
48704          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48705          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48706          * @param containingMessageChain A chain of errors to prepend any new errors found.
48707          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48708          */
48709         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48710             var errorInfo;
48711             var relatedInfo;
48712             var maybeKeys;
48713             var sourceStack;
48714             var targetStack;
48715             var maybeCount = 0;
48716             var depth = 0;
48717             var expandingFlags = 0 /* None */;
48718             var overflow = false;
48719             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48720             var lastSkippedInfo;
48721             var incompatibleStack = [];
48722             var inPropertyCheck = false;
48723             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48724             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48725             if (incompatibleStack.length) {
48726                 reportIncompatibleStack();
48727             }
48728             if (overflow) {
48729                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48730                 if (errorOutputContainer) {
48731                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48732                 }
48733             }
48734             else if (errorInfo) {
48735                 if (containingMessageChain) {
48736                     var chain = containingMessageChain();
48737                     if (chain) {
48738                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48739                         errorInfo = chain;
48740                     }
48741                 }
48742                 var relatedInformation = void 0;
48743                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48744                 if (headMessage && errorNode && !result && source.symbol) {
48745                     var links = getSymbolLinks(source.symbol);
48746                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48747                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48748                         if (helpfulRetry) {
48749                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48750                             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);
48751                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48752                         }
48753                     }
48754                 }
48755                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48756                 if (relatedInfo) {
48757                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48758                 }
48759                 if (errorOutputContainer) {
48760                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48761                 }
48762                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48763                     diagnostics.add(diag);
48764                 }
48765             }
48766             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48767                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48768             }
48769             return result !== 0 /* False */;
48770             function resetErrorInfo(saved) {
48771                 errorInfo = saved.errorInfo;
48772                 lastSkippedInfo = saved.lastSkippedInfo;
48773                 incompatibleStack = saved.incompatibleStack;
48774                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48775                 relatedInfo = saved.relatedInfo;
48776             }
48777             function captureErrorCalculationState() {
48778                 return {
48779                     errorInfo: errorInfo,
48780                     lastSkippedInfo: lastSkippedInfo,
48781                     incompatibleStack: incompatibleStack.slice(),
48782                     overrideNextErrorInfo: overrideNextErrorInfo,
48783                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48784                 };
48785             }
48786             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48787                 overrideNextErrorInfo++; // Suppress the next relation error
48788                 lastSkippedInfo = undefined; // Reset skipped info cache
48789                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48790             }
48791             function reportIncompatibleStack() {
48792                 var stack = incompatibleStack;
48793                 incompatibleStack = [];
48794                 var info = lastSkippedInfo;
48795                 lastSkippedInfo = undefined;
48796                 if (stack.length === 1) {
48797                     reportError.apply(void 0, stack[0]);
48798                     if (info) {
48799                         // Actually do the last relation error
48800                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48801                     }
48802                     return;
48803                 }
48804                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48805                 // we can build from left to right
48806                 var path = "";
48807                 var secondaryRootErrors = [];
48808                 while (stack.length) {
48809                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48810                     switch (msg.code) {
48811                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48812                             // Parenthesize a `new` if there is one
48813                             if (path.indexOf("new ") === 0) {
48814                                 path = "(" + path + ")";
48815                             }
48816                             var str = "" + args[0];
48817                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48818                             if (path.length === 0) {
48819                                 path = "" + str;
48820                             }
48821                             // Otherwise write a dotted name if possible
48822                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
48823                                 path = path + "." + str;
48824                             }
48825                             // Failing that, check if the name is already a computed name
48826                             else if (str[0] === "[" && str[str.length - 1] === "]") {
48827                                 path = "" + path + str;
48828                             }
48829                             // And finally write out a computed name as a last resort
48830                             else {
48831                                 path = path + "[" + str + "]";
48832                             }
48833                             break;
48834                         }
48835                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
48836                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
48837                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
48838                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
48839                             if (path.length === 0) {
48840                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
48841                                 // to unify (the with no arguments bit is excessive for printback) and print them back
48842                                 var mappedMsg = msg;
48843                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48844                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
48845                                 }
48846                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48847                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
48848                                 }
48849                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
48850                             }
48851                             else {
48852                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
48853                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48854                                     ? "new "
48855                                     : "";
48856                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
48857                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48858                                     ? ""
48859                                     : "...";
48860                                 path = "" + prefix + path + "(" + params + ")";
48861                             }
48862                             break;
48863                         }
48864                         default:
48865                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
48866                     }
48867                 }
48868                 if (path) {
48869                     reportError(path[path.length - 1] === ")"
48870                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
48871                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
48872                 }
48873                 else {
48874                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
48875                     secondaryRootErrors.shift();
48876                 }
48877                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
48878                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
48879                     var originalValue = msg.elidedInCompatabilityPyramid;
48880                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
48881                     reportError.apply(void 0, __spreadArrays([msg], args));
48882                     msg.elidedInCompatabilityPyramid = originalValue;
48883                 }
48884                 if (info) {
48885                     // Actually do the last relation error
48886                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48887                 }
48888             }
48889             function reportError(message, arg0, arg1, arg2, arg3) {
48890                 ts.Debug.assert(!!errorNode);
48891                 if (incompatibleStack.length)
48892                     reportIncompatibleStack();
48893                 if (message.elidedInCompatabilityPyramid)
48894                     return;
48895                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
48896             }
48897             function associateRelatedInfo(info) {
48898                 ts.Debug.assert(!!errorInfo);
48899                 if (!relatedInfo) {
48900                     relatedInfo = [info];
48901                 }
48902                 else {
48903                     relatedInfo.push(info);
48904                 }
48905             }
48906             function reportRelationError(message, source, target) {
48907                 if (incompatibleStack.length)
48908                     reportIncompatibleStack();
48909                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
48910                 if (target.flags & 262144 /* TypeParameter */) {
48911                     var constraint = getBaseConstraintOfType(target);
48912                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
48913                     if (constraintElab) {
48914                         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));
48915                     }
48916                     else {
48917                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
48918                     }
48919                 }
48920                 if (!message) {
48921                     if (relation === comparableRelation) {
48922                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
48923                     }
48924                     else if (sourceType === targetType) {
48925                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
48926                     }
48927                     else {
48928                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
48929                     }
48930                 }
48931                 reportError(message, sourceType, targetType);
48932             }
48933             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
48934                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
48935                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
48936                 if ((globalStringType === source && stringType === target) ||
48937                     (globalNumberType === source && numberType === target) ||
48938                     (globalBooleanType === source && booleanType === target) ||
48939                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
48940                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
48941                 }
48942             }
48943             /**
48944              * Try and elaborate array and tuple errors. Returns false
48945              * if we have found an elaboration, or we should ignore
48946              * any other elaborations when relating the `source` and
48947              * `target` types.
48948              */
48949             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
48950                 /**
48951                  * The spec for elaboration is:
48952                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48953                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
48954                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48955                  * - If the source an array then skip property elaborations if the target is a tuple.
48956                  */
48957                 if (isTupleType(source)) {
48958                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
48959                         if (reportErrors) {
48960                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48961                         }
48962                         return false;
48963                     }
48964                     return isTupleType(target) || isArrayType(target);
48965                 }
48966                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
48967                     if (reportErrors) {
48968                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48969                     }
48970                     return false;
48971                 }
48972                 if (isTupleType(target)) {
48973                     return isArrayType(source);
48974                 }
48975                 return true;
48976             }
48977             /**
48978              * Compare two types and return
48979              * * Ternary.True if they are related with no assumptions,
48980              * * Ternary.Maybe if they are related with assumptions of other relationships, or
48981              * * Ternary.False if they are not related.
48982              */
48983             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
48984                 if (reportErrors === void 0) { reportErrors = false; }
48985                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
48986                 // Before normalization: if `source` is type an object type, and `target` is primitive,
48987                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
48988                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
48989                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
48990                         return -1 /* True */;
48991                     }
48992                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
48993                     return 0 /* False */;
48994                 }
48995                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
48996                 // turn deferred type references into regular type references, simplify indexed access and
48997                 // conditional types, and resolve substitution types to either the substitution (on the source
48998                 // side) or the type variable (on the target side).
48999                 var source = getNormalizedType(originalSource, /*writing*/ false);
49000                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49001                 if (source === target)
49002                     return -1 /* True */;
49003                 if (relation === identityRelation) {
49004                     return isIdenticalTo(source, target);
49005                 }
49006                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49007                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49008                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49009                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49010                 // the target is exactly the constraint.
49011                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49012                     return -1 /* True */;
49013                 }
49014                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49015                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49016                 // First, see if we're even relating an object type to a union.
49017                 // Then see if the target is stripped down to a single non-union type.
49018                 // Note
49019                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49020                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49021                 //    when dealing with generics.
49022                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49023                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49024                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49025                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49026                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49027                         if (source === nullStrippedTarget)
49028                             return -1 /* True */;
49029                         target = nullStrippedTarget;
49030                     }
49031                 }
49032                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49033                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49034                     return -1 /* True */;
49035                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49036                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49037                 if (isPerformingExcessPropertyChecks) {
49038                     if (hasExcessProperties(source, target, reportErrors)) {
49039                         if (reportErrors) {
49040                             reportRelationError(headMessage, source, target);
49041                         }
49042                         return 0 /* False */;
49043                     }
49044                 }
49045                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49046                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49047                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49048                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49049                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49050                     if (reportErrors) {
49051                         var calls = getSignaturesOfType(source, 0 /* Call */);
49052                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49053                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49054                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49055                             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));
49056                         }
49057                         else {
49058                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49059                         }
49060                     }
49061                     return 0 /* False */;
49062                 }
49063                 var result = 0 /* False */;
49064                 var saveErrorInfo = captureErrorCalculationState();
49065                 // Note that these checks are specifically ordered to produce correct results. In particular,
49066                 // we need to deconstruct unions before intersections (because unions are always at the top),
49067                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49068                 if (source.flags & 1048576 /* Union */) {
49069                     result = relation === comparableRelation ?
49070                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49071                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49072                 }
49073                 else {
49074                     if (target.flags & 1048576 /* Union */) {
49075                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49076                     }
49077                     else if (target.flags & 2097152 /* Intersection */) {
49078                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49079                     }
49080                     else if (source.flags & 2097152 /* Intersection */) {
49081                         // Check to see if any constituents of the intersection are immediately related to the target.
49082                         //
49083                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49084                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49085                         // take care of this, or to not elaborate at all. For instance,
49086                         //
49087                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49088                         //
49089                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49090                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49091                         //
49092                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49093                         //          breaking the intersection apart.
49094                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49095                     }
49096                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49097                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49098                             resetErrorInfo(saveErrorInfo);
49099                         }
49100                     }
49101                 }
49102                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49103                     // The combined constraint of an intersection type is the intersection of the constraints of
49104                     // the constituents. When an intersection type contains instantiable types with union type
49105                     // constraints, there are situations where we need to examine the combined constraint. One is
49106                     // when the target is a union type. Another is when the intersection contains types belonging
49107                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49108                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49109                     // we need to check this constraint against a union on the target side. Also, given a type
49110                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49111                     // 'string & number | number & number' which reduces to just 'number'.
49112                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49113                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49114                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49115                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49116                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49117                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49118                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49119                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49120                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49121                                 resetErrorInfo(saveErrorInfo);
49122                             }
49123                         }
49124                     }
49125                 }
49126                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49127                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49128                 // examples that all should be errors, but aren't without this extra property check:
49129                 //
49130                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49131                 //
49132                 //   declare let wrong: { a: { y: string } };
49133                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49134                 //
49135                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49136                 //     x = y;  // Mismatched property in source intersection
49137                 //   }
49138                 //
49139                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49140                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49141                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49142                     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 */); }))) {
49143                     inPropertyCheck = true;
49144                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49145                     inPropertyCheck = false;
49146                 }
49147                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49148                 return result;
49149                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49150                     if (!result && reportErrors) {
49151                         source = originalSource.aliasSymbol ? originalSource : source;
49152                         target = originalTarget.aliasSymbol ? originalTarget : target;
49153                         var maybeSuppress = overrideNextErrorInfo > 0;
49154                         if (maybeSuppress) {
49155                             overrideNextErrorInfo--;
49156                         }
49157                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49158                             var currentError = errorInfo;
49159                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49160                             if (errorInfo !== currentError) {
49161                                 maybeSuppress = !!errorInfo;
49162                             }
49163                         }
49164                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49165                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49166                         }
49167                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49168                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49169                         }
49170                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49171                             var targetTypes = target.types;
49172                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49173                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49174                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49175                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49176                                 // do not report top error
49177                                 return result;
49178                             }
49179                         }
49180                         else {
49181                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49182                         }
49183                         if (!headMessage && maybeSuppress) {
49184                             lastSkippedInfo = [source, target];
49185                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49186                             return result;
49187                         }
49188                         reportRelationError(headMessage, source, target);
49189                     }
49190                 }
49191             }
49192             function isIdenticalTo(source, target) {
49193                 var flags = source.flags & target.flags;
49194                 if (!(flags & 66584576 /* Substructure */)) {
49195                     return 0 /* False */;
49196                 }
49197                 if (flags & 3145728 /* UnionOrIntersection */) {
49198                     var result_5 = eachTypeRelatedToSomeType(source, target);
49199                     if (result_5) {
49200                         result_5 &= eachTypeRelatedToSomeType(target, source);
49201                     }
49202                     return result_5;
49203                 }
49204                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49205             }
49206             function getTypeOfPropertyInTypes(types, name) {
49207                 var appendPropType = function (propTypes, type) {
49208                     type = getApparentType(type);
49209                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49210                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49211                     return ts.append(propTypes, propType);
49212                 };
49213                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49214             }
49215             function hasExcessProperties(source, target, reportErrors) {
49216                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49217                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49218                 }
49219                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49220                 if ((relation === assignableRelation || relation === comparableRelation) &&
49221                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49222                     return false;
49223                 }
49224                 var reducedTarget = target;
49225                 var checkTypes;
49226                 if (target.flags & 1048576 /* Union */) {
49227                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49228                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49229                 }
49230                 var _loop_13 = function (prop) {
49231                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49232                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49233                             if (reportErrors) {
49234                                 // Report error in terms of object types in the target as those are the only ones
49235                                 // we check in isKnownProperty.
49236                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49237                                 // We know *exactly* where things went wrong when comparing the types.
49238                                 // Use this property as the error node as this will be more helpful in
49239                                 // reasoning about what went wrong.
49240                                 if (!errorNode)
49241                                     return { value: ts.Debug.fail() };
49242                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49243                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49244                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49245                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49246                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49247                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49248                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49249                                         errorNode = prop.valueDeclaration.name;
49250                                     }
49251                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49252                                 }
49253                                 else {
49254                                     // use the property's value declaration if the property is assigned inside the literal itself
49255                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49256                                     var suggestion = void 0;
49257                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49258                                         var propDeclaration = prop.valueDeclaration;
49259                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49260                                         errorNode = propDeclaration;
49261                                         var name = propDeclaration.name;
49262                                         if (ts.isIdentifier(name)) {
49263                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49264                                         }
49265                                     }
49266                                     if (suggestion !== undefined) {
49267                                         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);
49268                                     }
49269                                     else {
49270                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49271                                     }
49272                                 }
49273                             }
49274                             return { value: true };
49275                         }
49276                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49277                             if (reportErrors) {
49278                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49279                             }
49280                             return { value: true };
49281                         }
49282                     }
49283                 };
49284                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49285                     var prop = _a[_i];
49286                     var state_5 = _loop_13(prop);
49287                     if (typeof state_5 === "object")
49288                         return state_5.value;
49289                 }
49290                 return false;
49291             }
49292             function shouldCheckAsExcessProperty(prop, container) {
49293                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49294             }
49295             function eachTypeRelatedToSomeType(source, target) {
49296                 var result = -1 /* True */;
49297                 var sourceTypes = source.types;
49298                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49299                     var sourceType = sourceTypes_1[_i];
49300                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49301                     if (!related) {
49302                         return 0 /* False */;
49303                     }
49304                     result &= related;
49305                 }
49306                 return result;
49307             }
49308             function typeRelatedToSomeType(source, target, reportErrors) {
49309                 var targetTypes = target.types;
49310                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49311                     return -1 /* True */;
49312                 }
49313                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49314                     var type = targetTypes_1[_i];
49315                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49316                     if (related) {
49317                         return related;
49318                     }
49319                 }
49320                 if (reportErrors) {
49321                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49322                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49323                 }
49324                 return 0 /* False */;
49325             }
49326             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49327                 var result = -1 /* True */;
49328                 var targetTypes = target.types;
49329                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49330                     var targetType = targetTypes_2[_i];
49331                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49332                     if (!related) {
49333                         return 0 /* False */;
49334                     }
49335                     result &= related;
49336                 }
49337                 return result;
49338             }
49339             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49340                 var sourceTypes = source.types;
49341                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49342                     return -1 /* True */;
49343                 }
49344                 var len = sourceTypes.length;
49345                 for (var i = 0; i < len; i++) {
49346                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49347                     if (related) {
49348                         return related;
49349                     }
49350                 }
49351                 return 0 /* False */;
49352             }
49353             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49354                 var result = -1 /* True */;
49355                 var sourceTypes = source.types;
49356                 for (var i = 0; i < sourceTypes.length; i++) {
49357                     var sourceType = sourceTypes[i];
49358                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49359                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49360                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49361                         if (related_1) {
49362                             result &= related_1;
49363                             continue;
49364                         }
49365                     }
49366                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49367                     if (!related) {
49368                         return 0 /* False */;
49369                     }
49370                     result &= related;
49371                 }
49372                 return result;
49373             }
49374             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49375                 if (sources === void 0) { sources = ts.emptyArray; }
49376                 if (targets === void 0) { targets = ts.emptyArray; }
49377                 if (variances === void 0) { variances = ts.emptyArray; }
49378                 if (sources.length !== targets.length && relation === identityRelation) {
49379                     return 0 /* False */;
49380                 }
49381                 var length = sources.length <= targets.length ? sources.length : targets.length;
49382                 var result = -1 /* True */;
49383                 for (var i = 0; i < length; i++) {
49384                     // When variance information isn't available we default to covariance. This happens
49385                     // in the process of computing variance information for recursive types and when
49386                     // comparing 'this' type arguments.
49387                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49388                     var variance = varianceFlags & 7 /* VarianceMask */;
49389                     // We ignore arguments for independent type parameters (because they're never witnessed).
49390                     if (variance !== 4 /* Independent */) {
49391                         var s = sources[i];
49392                         var t = targets[i];
49393                         var related = -1 /* True */;
49394                         if (varianceFlags & 8 /* Unmeasurable */) {
49395                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49396                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49397                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49398                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49399                         }
49400                         else if (variance === 1 /* Covariant */) {
49401                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49402                         }
49403                         else if (variance === 2 /* Contravariant */) {
49404                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49405                         }
49406                         else if (variance === 3 /* Bivariant */) {
49407                             // In the bivariant case we first compare contravariantly without reporting
49408                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49409                             // reporting. Thus, error elaboration will be based on the the covariant check,
49410                             // which is generally easier to reason about.
49411                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49412                             if (!related) {
49413                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49414                             }
49415                         }
49416                         else {
49417                             // In the invariant case we first compare covariantly, and only when that
49418                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49419                             // will typically be based on the covariant check.
49420                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49421                             if (related) {
49422                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49423                             }
49424                         }
49425                         if (!related) {
49426                             return 0 /* False */;
49427                         }
49428                         result &= related;
49429                     }
49430                 }
49431                 return result;
49432             }
49433             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49434             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49435             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49436             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49437             // and issue an error. Otherwise, actually compare the structure of the two types.
49438             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49439                 if (overflow) {
49440                     return 0 /* False */;
49441                 }
49442                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49443                 var entry = relation.get(id);
49444                 if (entry !== undefined) {
49445                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49446                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49447                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49448                     }
49449                     else {
49450                         if (outofbandVarianceMarkerHandler) {
49451                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49452                             var saved = entry & 24 /* ReportsMask */;
49453                             if (saved & 8 /* ReportsUnmeasurable */) {
49454                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49455                             }
49456                             if (saved & 16 /* ReportsUnreliable */) {
49457                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49458                             }
49459                         }
49460                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49461                     }
49462                 }
49463                 if (!maybeKeys) {
49464                     maybeKeys = [];
49465                     sourceStack = [];
49466                     targetStack = [];
49467                 }
49468                 else {
49469                     for (var i = 0; i < maybeCount; i++) {
49470                         // If source and target are already being compared, consider them related with assumptions
49471                         if (id === maybeKeys[i]) {
49472                             return 1 /* Maybe */;
49473                         }
49474                     }
49475                     if (depth === 100) {
49476                         overflow = true;
49477                         return 0 /* False */;
49478                     }
49479                 }
49480                 var maybeStart = maybeCount;
49481                 maybeKeys[maybeCount] = id;
49482                 maybeCount++;
49483                 sourceStack[depth] = source;
49484                 targetStack[depth] = target;
49485                 depth++;
49486                 var saveExpandingFlags = expandingFlags;
49487                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49488                     expandingFlags |= 1 /* Source */;
49489                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49490                     expandingFlags |= 2 /* Target */;
49491                 var originalHandler;
49492                 var propagatingVarianceFlags = 0;
49493                 if (outofbandVarianceMarkerHandler) {
49494                     originalHandler = outofbandVarianceMarkerHandler;
49495                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49496                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49497                         return originalHandler(onlyUnreliable);
49498                     };
49499                 }
49500                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49501                 if (outofbandVarianceMarkerHandler) {
49502                     outofbandVarianceMarkerHandler = originalHandler;
49503                 }
49504                 expandingFlags = saveExpandingFlags;
49505                 depth--;
49506                 if (result) {
49507                     if (result === -1 /* True */ || depth === 0) {
49508                         // If result is definitely true, record all maybe keys as having succeeded
49509                         for (var i = maybeStart; i < maybeCount; i++) {
49510                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49511                         }
49512                         maybeCount = maybeStart;
49513                     }
49514                 }
49515                 else {
49516                     // A false result goes straight into global cache (when something is false under
49517                     // assumptions it will also be false without assumptions)
49518                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49519                     maybeCount = maybeStart;
49520                 }
49521                 return result;
49522             }
49523             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49524                 if (intersectionState & 4 /* PropertyCheck */) {
49525                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49526                 }
49527                 var flags = source.flags & target.flags;
49528                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49529                     if (flags & 4194304 /* Index */) {
49530                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49531                     }
49532                     var result_6 = 0 /* False */;
49533                     if (flags & 8388608 /* IndexedAccess */) {
49534                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49535                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49536                                 return result_6;
49537                             }
49538                         }
49539                     }
49540                     if (flags & 16777216 /* Conditional */) {
49541                         if (source.root.isDistributive === target.root.isDistributive) {
49542                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49543                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49544                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49545                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49546                                             return result_6;
49547                                         }
49548                                     }
49549                                 }
49550                             }
49551                         }
49552                     }
49553                     if (flags & 33554432 /* Substitution */) {
49554                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49555                     }
49556                     return 0 /* False */;
49557                 }
49558                 var result;
49559                 var originalErrorInfo;
49560                 var varianceCheckFailed = false;
49561                 var saveErrorInfo = captureErrorCalculationState();
49562                 // We limit alias variance probing to only object and conditional types since their alias behavior
49563                 // is more predictable than other, interned types, which may or may not have an alias depending on
49564                 // the order in which things were checked.
49565                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49566                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49567                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49568                     var variances = getAliasVariances(source.aliasSymbol);
49569                     if (variances === ts.emptyArray) {
49570                         return 1 /* Maybe */;
49571                     }
49572                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49573                     if (varianceResult !== undefined) {
49574                         return varianceResult;
49575                     }
49576                 }
49577                 if (target.flags & 262144 /* TypeParameter */) {
49578                     // 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].
49579                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49580                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49581                             var templateType = getTemplateTypeFromMappedType(source);
49582                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49583                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49584                                 return result;
49585                             }
49586                         }
49587                     }
49588                 }
49589                 else if (target.flags & 4194304 /* Index */) {
49590                     // A keyof S is related to a keyof T if T is related to S.
49591                     if (source.flags & 4194304 /* Index */) {
49592                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49593                             return result;
49594                         }
49595                     }
49596                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49597                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49598                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49599                     if (constraint) {
49600                         // We require Ternary.True here such that circular constraints don't cause
49601                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49602                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49603                         // related to other types.
49604                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49605                             return -1 /* True */;
49606                         }
49607                     }
49608                 }
49609                 else if (target.flags & 8388608 /* IndexedAccess */) {
49610                     // A type S is related to a type T[K] if S is related to C, where C is the base
49611                     // constraint of T[K] for writing.
49612                     if (relation !== identityRelation) {
49613                         var objectType = target.objectType;
49614                         var indexType = target.indexType;
49615                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49616                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49617                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49618                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49619                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49620                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49621                                 return result;
49622                             }
49623                         }
49624                     }
49625                 }
49626                 else if (isGenericMappedType(target)) {
49627                     // A source type T is related to a target type { [P in X]: T[P] }
49628                     var template = getTemplateTypeFromMappedType(target);
49629                     var modifiers = getMappedTypeModifiers(target);
49630                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49631                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49632                             template.indexType === getTypeParameterFromMappedType(target)) {
49633                             return -1 /* True */;
49634                         }
49635                         if (!isGenericMappedType(source)) {
49636                             var targetConstraint = getConstraintTypeFromMappedType(target);
49637                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49638                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49639                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49640                             // 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.
49641                             // 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.
49642                             if (includeOptional
49643                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49644                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49645                                 var typeParameter = getTypeParameterFromMappedType(target);
49646                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49647                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49648                                 var templateType = getTemplateTypeFromMappedType(target);
49649                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49650                                     return result;
49651                                 }
49652                             }
49653                             originalErrorInfo = errorInfo;
49654                             resetErrorInfo(saveErrorInfo);
49655                         }
49656                     }
49657                 }
49658                 if (source.flags & 8650752 /* TypeVariable */) {
49659                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49660                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49661                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49662                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49663                         }
49664                         if (result) {
49665                             resetErrorInfo(saveErrorInfo);
49666                             return result;
49667                         }
49668                     }
49669                     else {
49670                         var constraint = getConstraintOfType(source);
49671                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49672                             // A type variable with no constraint is not related to the non-primitive object type.
49673                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49674                                 resetErrorInfo(saveErrorInfo);
49675                                 return result;
49676                             }
49677                         }
49678                         // 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
49679                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49680                             resetErrorInfo(saveErrorInfo);
49681                             return result;
49682                         }
49683                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49684                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49685                             resetErrorInfo(saveErrorInfo);
49686                             return result;
49687                         }
49688                     }
49689                 }
49690                 else if (source.flags & 4194304 /* Index */) {
49691                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49692                         resetErrorInfo(saveErrorInfo);
49693                         return result;
49694                     }
49695                 }
49696                 else if (source.flags & 16777216 /* Conditional */) {
49697                     if (target.flags & 16777216 /* Conditional */) {
49698                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49699                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49700                         // and Y1 is related to Y2.
49701                         var sourceParams = source.root.inferTypeParameters;
49702                         var sourceExtends = source.extendsType;
49703                         var mapper = void 0;
49704                         if (sourceParams) {
49705                             // If the source has infer type parameters, we instantiate them in the context of the target
49706                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49707                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49708                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49709                             mapper = ctx.mapper;
49710                         }
49711                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49712                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49713                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49714                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49715                             }
49716                             if (result) {
49717                                 resetErrorInfo(saveErrorInfo);
49718                                 return result;
49719                             }
49720                         }
49721                     }
49722                     else {
49723                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49724                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49725                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49726                         if (distributiveConstraint) {
49727                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49728                                 resetErrorInfo(saveErrorInfo);
49729                                 return result;
49730                             }
49731                         }
49732                     }
49733                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49734                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49735                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49736                     if (defaultConstraint) {
49737                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49738                             resetErrorInfo(saveErrorInfo);
49739                             return result;
49740                         }
49741                     }
49742                 }
49743                 else {
49744                     // An empty object type is related to any mapped type that includes a '?' modifier.
49745                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49746                         return -1 /* True */;
49747                     }
49748                     if (isGenericMappedType(target)) {
49749                         if (isGenericMappedType(source)) {
49750                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49751                                 resetErrorInfo(saveErrorInfo);
49752                                 return result;
49753                             }
49754                         }
49755                         return 0 /* False */;
49756                     }
49757                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49758                     if (relation !== identityRelation) {
49759                         source = getApparentType(source);
49760                     }
49761                     else if (isGenericMappedType(source)) {
49762                         return 0 /* False */;
49763                     }
49764                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49765                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49766                         // We have type references to the same generic type, and the type references are not marker
49767                         // type references (which are intended by be compared structurally). Obtain the variance
49768                         // information for the type parameters and relate the type arguments accordingly.
49769                         var variances = getVariances(source.target);
49770                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49771                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49772                         // recursive instantiations of the generic type.
49773                         if (variances === ts.emptyArray) {
49774                             return 1 /* Maybe */;
49775                         }
49776                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49777                         if (varianceResult !== undefined) {
49778                             return varianceResult;
49779                         }
49780                     }
49781                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49782                         if (relation !== identityRelation) {
49783                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49784                         }
49785                         else {
49786                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49787                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49788                             return 0 /* False */;
49789                         }
49790                     }
49791                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49792                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49793                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49794                         return 0 /* False */;
49795                     }
49796                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49797                     // it may hold in a structural comparison.
49798                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49799                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49800                     // relates to X. Thus, we include intersection types on the source side here.
49801                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49802                         // Report structural errors only if we haven't reported any errors yet
49803                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49804                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49805                         if (result) {
49806                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49807                             if (result) {
49808                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49809                                 if (result) {
49810                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49811                                     if (result) {
49812                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49813                                     }
49814                                 }
49815                             }
49816                         }
49817                         if (varianceCheckFailed && result) {
49818                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49819                         }
49820                         else if (result) {
49821                             return result;
49822                         }
49823                     }
49824                     // If S is an object type and T is a discriminated union, S may be related to T if
49825                     // there exists a constituent of T for every combination of the discriminants of S
49826                     // with respect to T. We do not report errors here, as we will use the existing
49827                     // error result from checking each constituent of the union.
49828                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
49829                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
49830                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
49831                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
49832                             if (result_7) {
49833                                 return result_7;
49834                             }
49835                         }
49836                     }
49837                 }
49838                 return 0 /* False */;
49839                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
49840                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
49841                         return result;
49842                     }
49843                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
49844                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
49845                         // have to allow a structural fallback check
49846                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
49847                         // be assuming identity of the type parameter.
49848                         originalErrorInfo = undefined;
49849                         resetErrorInfo(saveErrorInfo);
49850                         return undefined;
49851                     }
49852                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
49853                     varianceCheckFailed = !allowStructuralFallback;
49854                     // The type arguments did not relate appropriately, but it may be because we have no variance
49855                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
49856                     // arguments). It might also be the case that the target type has a 'void' type argument for
49857                     // a covariant type parameter that is only used in return positions within the generic type
49858                     // (in which case any type argument is permitted on the source side). In those cases we proceed
49859                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
49860                     // related and we can return here.
49861                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
49862                         // In some cases generic types that are covariant in regular type checking mode become
49863                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
49864                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
49865                         // types are invariant, if any of the type parameters are invariant we reset the reported
49866                         // errors and instead force a structural comparison (which will include elaborations that
49867                         // reveal the reason).
49868                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
49869                         // we can return `False` early here to skip calculating the structural error message we don't need.
49870                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
49871                             return 0 /* False */;
49872                         }
49873                         // We remember the original error information so we can restore it in case the structural
49874                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
49875                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
49876                         originalErrorInfo = errorInfo;
49877                         resetErrorInfo(saveErrorInfo);
49878                     }
49879                 }
49880             }
49881             function reportUnmeasurableMarkers(p) {
49882                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49883                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
49884                 }
49885                 return p;
49886             }
49887             function reportUnreliableMarkers(p) {
49888                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49889                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
49890                 }
49891                 return p;
49892             }
49893             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
49894             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
49895             // that S and T are contra-variant whereas X and Y are co-variant.
49896             function mappedTypeRelatedTo(source, target, reportErrors) {
49897                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
49898                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
49899                 if (modifiersRelated) {
49900                     var result_8;
49901                     var targetConstraint = getConstraintTypeFromMappedType(target);
49902                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
49903                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
49904                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
49905                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
49906                     }
49907                 }
49908                 return 0 /* False */;
49909             }
49910             function typeRelatedToDiscriminatedType(source, target) {
49911                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
49912                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
49913                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
49914                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
49915                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
49916                 //    'target' are related to a property in 'source'.
49917                 //
49918                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
49919                 //       for examples.
49920                 var sourceProperties = getPropertiesOfType(source);
49921                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
49922                 if (!sourcePropertiesFiltered)
49923                     return 0 /* False */;
49924                 // Though we could compute the number of combinations as we generate
49925                 // the matrix, this would incur additional memory overhead due to
49926                 // array allocations. To reduce this overhead, we first compute
49927                 // the number of combinations to ensure we will not surpass our
49928                 // fixed limit before incurring the cost of any allocations:
49929                 var numCombinations = 1;
49930                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
49931                     var sourceProperty = sourcePropertiesFiltered_1[_i];
49932                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
49933                     if (numCombinations > 25) {
49934                         // We've reached the complexity limit.
49935                         return 0 /* False */;
49936                     }
49937                 }
49938                 // Compute the set of types for each discriminant property.
49939                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
49940                 var excludedProperties = ts.createUnderscoreEscapedMap();
49941                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49942                     var sourceProperty = sourcePropertiesFiltered[i];
49943                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
49944                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
49945                         ? sourcePropertyType.types
49946                         : [sourcePropertyType];
49947                     excludedProperties.set(sourceProperty.escapedName, true);
49948                 }
49949                 // Match each combination of the cartesian product of discriminant properties to one or more
49950                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
49951                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
49952                 var matchingTypes = [];
49953                 var _loop_14 = function (combination) {
49954                     var hasMatch = false;
49955                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
49956                         var type = _a[_i];
49957                         var _loop_15 = function (i) {
49958                             var sourceProperty = sourcePropertiesFiltered[i];
49959                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
49960                             if (!targetProperty)
49961                                 return "continue-outer";
49962                             if (sourceProperty === targetProperty)
49963                                 return "continue";
49964                             // We compare the source property to the target in the context of a single discriminant type.
49965                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
49966                             // If the target property could not be found, or if the properties were not related,
49967                             // then this constituent is not a match.
49968                             if (!related) {
49969                                 return "continue-outer";
49970                             }
49971                         };
49972                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49973                             var state_7 = _loop_15(i);
49974                             switch (state_7) {
49975                                 case "continue-outer": continue outer;
49976                             }
49977                         }
49978                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
49979                         hasMatch = true;
49980                     }
49981                     if (!hasMatch) {
49982                         return { value: 0 /* False */ };
49983                     }
49984                 };
49985                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
49986                     var combination = discriminantCombinations_1[_a];
49987                     var state_6 = _loop_14(combination);
49988                     if (typeof state_6 === "object")
49989                         return state_6.value;
49990                 }
49991                 // Compare the remaining non-discriminant properties of each match.
49992                 var result = -1 /* True */;
49993                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
49994                     var type = matchingTypes_1[_b];
49995                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
49996                     if (result) {
49997                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
49998                         if (result) {
49999                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50000                             if (result) {
50001                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50002                                 if (result) {
50003                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50004                                 }
50005                             }
50006                         }
50007                     }
50008                     if (!result) {
50009                         return result;
50010                     }
50011                 }
50012                 return result;
50013             }
50014             function excludeProperties(properties, excludedProperties) {
50015                 if (!excludedProperties || properties.length === 0)
50016                     return properties;
50017                 var result;
50018                 for (var i = 0; i < properties.length; i++) {
50019                     if (!excludedProperties.has(properties[i].escapedName)) {
50020                         if (result) {
50021                             result.push(properties[i]);
50022                         }
50023                     }
50024                     else if (!result) {
50025                         result = properties.slice(0, i);
50026                     }
50027                 }
50028                 return result || properties;
50029             }
50030             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50031                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50032                 var source = getTypeOfSourceProperty(sourceProp);
50033                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50034                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50035                     var links = getSymbolLinks(targetProp);
50036                     ts.Debug.assertIsDefined(links.deferralParent);
50037                     ts.Debug.assertIsDefined(links.deferralConstituents);
50038                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50039                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50040                     var targetTypes = links.deferralConstituents;
50041                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50042                         var targetType = targetTypes_3[_i];
50043                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50044                         if (!unionParent) {
50045                             if (!related) {
50046                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50047                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50048                             }
50049                             result_9 &= related;
50050                         }
50051                         else {
50052                             if (related) {
50053                                 return related;
50054                             }
50055                         }
50056                     }
50057                     if (unionParent && !result_9 && targetIsOptional) {
50058                         result_9 = isRelatedTo(source, undefinedType);
50059                     }
50060                     if (unionParent && !result_9 && reportErrors) {
50061                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50062                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50063                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50064                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50065                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50066                     }
50067                     return result_9;
50068                 }
50069                 else {
50070                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50071                 }
50072             }
50073             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50074                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50075                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50076                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50077                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50078                         if (reportErrors) {
50079                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50080                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50081                             }
50082                             else {
50083                                 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));
50084                             }
50085                         }
50086                         return 0 /* False */;
50087                     }
50088                 }
50089                 else if (targetPropFlags & 16 /* Protected */) {
50090                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50091                         if (reportErrors) {
50092                             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));
50093                         }
50094                         return 0 /* False */;
50095                     }
50096                 }
50097                 else if (sourcePropFlags & 16 /* Protected */) {
50098                     if (reportErrors) {
50099                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50100                     }
50101                     return 0 /* False */;
50102                 }
50103                 // If the target comes from a partial union prop, allow `undefined` in the target type
50104                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50105                 if (!related) {
50106                     if (reportErrors) {
50107                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50108                     }
50109                     return 0 /* False */;
50110                 }
50111                 // When checking for comparability, be more lenient with optional properties.
50112                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50113                     // TypeScript 1.0 spec (April 2014): 3.8.3
50114                     // S is a subtype of a type T, and T is a supertype of S if ...
50115                     // S' and T are object types and, for each member M in T..
50116                     // M is a property and S' contains a property N where
50117                     // if M is a required property, N is also a required property
50118                     // (M - property in T)
50119                     // (N - property in S)
50120                     if (reportErrors) {
50121                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50122                     }
50123                     return 0 /* False */;
50124                 }
50125                 return related;
50126             }
50127             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50128                 var shouldSkipElaboration = false;
50129                 // give specific error in case where private names have the same description
50130                 if (unmatchedProperty.valueDeclaration
50131                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50132                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50133                     && source.symbol
50134                     && source.symbol.flags & 32 /* Class */) {
50135                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50136                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50137                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50138                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50139                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50140                         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));
50141                         return;
50142                     }
50143                 }
50144                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50145                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50146                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50147                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50148                 }
50149                 if (props.length === 1) {
50150                     var propName = symbolToString(unmatchedProperty);
50151                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50152                     if (ts.length(unmatchedProperty.declarations)) {
50153                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50154                     }
50155                     if (shouldSkipElaboration && errorInfo) {
50156                         overrideNextErrorInfo++;
50157                     }
50158                 }
50159                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50160                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50161                         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);
50162                     }
50163                     else {
50164                         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(", "));
50165                     }
50166                     if (shouldSkipElaboration && errorInfo) {
50167                         overrideNextErrorInfo++;
50168                     }
50169                 }
50170                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50171             }
50172             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50173                 if (relation === identityRelation) {
50174                     return propertiesIdenticalTo(source, target, excludedProperties);
50175                 }
50176                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50177                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50178                 if (unmatchedProperty) {
50179                     if (reportErrors) {
50180                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50181                     }
50182                     return 0 /* False */;
50183                 }
50184                 if (isObjectLiteralType(target)) {
50185                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50186                         var sourceProp = _a[_i];
50187                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50188                             var sourceType = getTypeOfSymbol(sourceProp);
50189                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50190                                 if (reportErrors) {
50191                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50192                                 }
50193                                 return 0 /* False */;
50194                             }
50195                         }
50196                     }
50197                 }
50198                 var result = -1 /* True */;
50199                 if (isTupleType(target)) {
50200                     var targetRestType = getRestTypeOfTupleType(target);
50201                     if (targetRestType) {
50202                         if (!isTupleType(source)) {
50203                             return 0 /* False */;
50204                         }
50205                         var sourceRestType = getRestTypeOfTupleType(source);
50206                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50207                             if (reportErrors) {
50208                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50209                             }
50210                             return 0 /* False */;
50211                         }
50212                         var targetCount = getTypeReferenceArity(target) - 1;
50213                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50214                         var sourceTypeArguments = getTypeArguments(source);
50215                         for (var i = targetCount; i < sourceCount; i++) {
50216                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50217                             if (!related) {
50218                                 if (reportErrors) {
50219                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50220                                 }
50221                                 return 0 /* False */;
50222                             }
50223                             result &= related;
50224                         }
50225                     }
50226                 }
50227                 // 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_
50228                 // from the target union, across all members
50229                 var properties = getPropertiesOfType(target);
50230                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50231                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50232                     var targetProp = _c[_b];
50233                     var name = targetProp.escapedName;
50234                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50235                         var sourceProp = getPropertyOfType(source, name);
50236                         if (sourceProp && sourceProp !== targetProp) {
50237                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50238                             if (!related) {
50239                                 return 0 /* False */;
50240                             }
50241                             result &= related;
50242                         }
50243                     }
50244                 }
50245                 return result;
50246             }
50247             function propertiesIdenticalTo(source, target, excludedProperties) {
50248                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50249                     return 0 /* False */;
50250                 }
50251                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50252                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50253                 if (sourceProperties.length !== targetProperties.length) {
50254                     return 0 /* False */;
50255                 }
50256                 var result = -1 /* True */;
50257                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50258                     var sourceProp = sourceProperties_1[_i];
50259                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50260                     if (!targetProp) {
50261                         return 0 /* False */;
50262                     }
50263                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50264                     if (!related) {
50265                         return 0 /* False */;
50266                     }
50267                     result &= related;
50268                 }
50269                 return result;
50270             }
50271             function signaturesRelatedTo(source, target, kind, reportErrors) {
50272                 if (relation === identityRelation) {
50273                     return signaturesIdenticalTo(source, target, kind);
50274                 }
50275                 if (target === anyFunctionType || source === anyFunctionType) {
50276                     return -1 /* True */;
50277                 }
50278                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50279                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50280                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50281                     0 /* Call */ : kind);
50282                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50283                     0 /* Call */ : kind);
50284                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50285                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50286                         // An abstract constructor type is not assignable to a non-abstract constructor type
50287                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50288                         // check we perform for an extends clause excludes construct signatures from the target,
50289                         // so this check never proceeds.
50290                         if (reportErrors) {
50291                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50292                         }
50293                         return 0 /* False */;
50294                     }
50295                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50296                         return 0 /* False */;
50297                     }
50298                 }
50299                 var result = -1 /* True */;
50300                 var saveErrorInfo = captureErrorCalculationState();
50301                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50302                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50303                     // We have instantiations of the same anonymous type (which typically will be the type of a
50304                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50305                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50306                     // as they are known to always be the same.
50307                     for (var i = 0; i < targetSignatures.length; i++) {
50308                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50309                         if (!related) {
50310                             return 0 /* False */;
50311                         }
50312                         result &= related;
50313                     }
50314                 }
50315                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50316                     // For simple functions (functions with a single signature) we only erase type parameters for
50317                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50318                     // in the context of the target signature before checking the relationship. Ideally we'd do
50319                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50320                     // to the quadratic nature of the logic below.
50321                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50322                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50323                 }
50324                 else {
50325                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50326                         var t = targetSignatures_1[_i];
50327                         // Only elaborate errors from the first failure
50328                         var shouldElaborateErrors = reportErrors;
50329                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50330                             var s = sourceSignatures_1[_a];
50331                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50332                             if (related) {
50333                                 result &= related;
50334                                 resetErrorInfo(saveErrorInfo);
50335                                 continue outer;
50336                             }
50337                             shouldElaborateErrors = false;
50338                         }
50339                         if (shouldElaborateErrors) {
50340                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50341                         }
50342                         return 0 /* False */;
50343                     }
50344                 }
50345                 return result;
50346             }
50347             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50348                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50349                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50350                 }
50351                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50352             }
50353             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50354                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50355                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50356                 }
50357                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50358             }
50359             /**
50360              * See signatureAssignableTo, compareSignaturesIdentical
50361              */
50362             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50363                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50364             }
50365             function signaturesIdenticalTo(source, target, kind) {
50366                 var sourceSignatures = getSignaturesOfType(source, kind);
50367                 var targetSignatures = getSignaturesOfType(target, kind);
50368                 if (sourceSignatures.length !== targetSignatures.length) {
50369                     return 0 /* False */;
50370                 }
50371                 var result = -1 /* True */;
50372                 for (var i = 0; i < sourceSignatures.length; i++) {
50373                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50374                     if (!related) {
50375                         return 0 /* False */;
50376                     }
50377                     result &= related;
50378                 }
50379                 return result;
50380             }
50381             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50382                 var result = -1 /* True */;
50383                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50384                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50385                     var prop = props_2[_i];
50386                     // Skip over ignored JSX and symbol-named members
50387                     if (isIgnoredJsxProperty(source, prop)) {
50388                         continue;
50389                     }
50390                     var nameType = getSymbolLinks(prop).nameType;
50391                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50392                         continue;
50393                     }
50394                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50395                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50396                         if (!related) {
50397                             if (reportErrors) {
50398                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50399                             }
50400                             return 0 /* False */;
50401                         }
50402                         result &= related;
50403                     }
50404                 }
50405                 return result;
50406             }
50407             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50408                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50409                 if (!related && reportErrors) {
50410                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50411                 }
50412                 return related;
50413             }
50414             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50415                 if (relation === identityRelation) {
50416                     return indexTypesIdenticalTo(source, target, kind);
50417                 }
50418                 var targetType = getIndexTypeOfType(target, kind);
50419                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50420                     // Index signature of type any permits assignment from everything but primitives
50421                     return -1 /* True */;
50422                 }
50423                 if (isGenericMappedType(source)) {
50424                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50425                     // if T is related to U.
50426                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50427                 }
50428                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50429                 if (indexType) {
50430                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50431                 }
50432                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50433                     // Intersection constituents are never considered to have an inferred index signature
50434                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50435                     if (related && kind === 0 /* String */) {
50436                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50437                         if (numberIndexType) {
50438                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50439                         }
50440                     }
50441                     return related;
50442                 }
50443                 if (reportErrors) {
50444                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50445                 }
50446                 return 0 /* False */;
50447             }
50448             function indexTypesIdenticalTo(source, target, indexKind) {
50449                 var targetInfo = getIndexInfoOfType(target, indexKind);
50450                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50451                 if (!sourceInfo && !targetInfo) {
50452                     return -1 /* True */;
50453                 }
50454                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50455                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50456                 }
50457                 return 0 /* False */;
50458             }
50459             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50460                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50461                     return true;
50462                 }
50463                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50464                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50465                 // A public, protected and private signature is assignable to a private signature.
50466                 if (targetAccessibility === 8 /* Private */) {
50467                     return true;
50468                 }
50469                 // A public and protected signature is assignable to a protected signature.
50470                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50471                     return true;
50472                 }
50473                 // Only a public signature is assignable to public signature.
50474                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50475                     return true;
50476                 }
50477                 if (reportErrors) {
50478                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50479                 }
50480                 return false;
50481             }
50482         }
50483         function getBestMatchingType(source, target, isRelatedTo) {
50484             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50485             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50486                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50487                 findBestTypeForObjectLiteral(source, target) ||
50488                 findBestTypeForInvokable(source, target) ||
50489                 findMostOverlappyType(source, target);
50490         }
50491         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50492             // undefined=unknown, true=discriminated, false=not discriminated
50493             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50494             var discriminable = target.types.map(function (_) { return undefined; });
50495             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50496                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50497                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50498                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50499                     continue;
50500                 }
50501                 var i = 0;
50502                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50503                     var type = _c[_b];
50504                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50505                     if (targetType && related(getDiscriminatingType(), targetType)) {
50506                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50507                     }
50508                     else {
50509                         discriminable[i] = false;
50510                     }
50511                     i++;
50512                 }
50513             }
50514             var match = discriminable.indexOf(/*searchElement*/ true);
50515             // make sure exactly 1 matches before returning it
50516             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50517         }
50518         /**
50519          * A type is 'weak' if it is an object type with at least one optional property
50520          * and no required properties, call/construct signatures or index signatures
50521          */
50522         function isWeakType(type) {
50523             if (type.flags & 524288 /* Object */) {
50524                 var resolved = resolveStructuredTypeMembers(type);
50525                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50526                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50527                     resolved.properties.length > 0 &&
50528                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50529             }
50530             if (type.flags & 2097152 /* Intersection */) {
50531                 return ts.every(type.types, isWeakType);
50532             }
50533             return false;
50534         }
50535         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50536             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50537                 var prop = _a[_i];
50538                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50539                     return true;
50540                 }
50541             }
50542             return false;
50543         }
50544         // Return a type reference where the source type parameter is replaced with the target marker
50545         // type, and flag the result as a marker type reference.
50546         function getMarkerTypeReference(type, source, target) {
50547             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50548             result.objectFlags |= 8192 /* MarkerType */;
50549             return result;
50550         }
50551         function getAliasVariances(symbol) {
50552             var links = getSymbolLinks(symbol);
50553             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50554                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50555                 type.aliasTypeArgumentsContainsMarker = true;
50556                 return type;
50557             });
50558         }
50559         // Return an array containing the variance of each type parameter. The variance is effectively
50560         // a digest of the type comparisons that occur for each type argument when instantiations of the
50561         // generic type are structurally compared. We infer the variance information by comparing
50562         // instantiations of the generic type for type arguments with known relations. The function
50563         // returns the emptyArray singleton when invoked recursively for the given generic type.
50564         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50565             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50566             var variances = cache.variances;
50567             if (!variances) {
50568                 // The emptyArray singleton is used to signal a recursive invocation.
50569                 cache.variances = ts.emptyArray;
50570                 variances = [];
50571                 var _loop_16 = function (tp) {
50572                     var unmeasurable = false;
50573                     var unreliable = false;
50574                     var oldHandler = outofbandVarianceMarkerHandler;
50575                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50576                     // We first compare instantiations where the type parameter is replaced with
50577                     // marker types that have a known subtype relationship. From this we can infer
50578                     // invariance, covariance, contravariance or bivariance.
50579                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50580                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50581                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50582                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50583                     // If the instantiations appear to be related bivariantly it may be because the
50584                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50585                     // type). To determine this we compare instantiations where the type parameter is
50586                     // replaced with marker types that are known to be unrelated.
50587                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50588                         variance = 4 /* Independent */;
50589                     }
50590                     outofbandVarianceMarkerHandler = oldHandler;
50591                     if (unmeasurable || unreliable) {
50592                         if (unmeasurable) {
50593                             variance |= 8 /* Unmeasurable */;
50594                         }
50595                         if (unreliable) {
50596                             variance |= 16 /* Unreliable */;
50597                         }
50598                     }
50599                     variances.push(variance);
50600                 };
50601                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50602                     var tp = typeParameters_1[_i];
50603                     _loop_16(tp);
50604                 }
50605                 cache.variances = variances;
50606             }
50607             return variances;
50608         }
50609         function getVariances(type) {
50610             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50611             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50612                 return arrayVariances;
50613             }
50614             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50615         }
50616         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50617         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50618         function hasCovariantVoidArgument(typeArguments, variances) {
50619             for (var i = 0; i < variances.length; i++) {
50620                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50621                     return true;
50622                 }
50623             }
50624             return false;
50625         }
50626         function isUnconstrainedTypeParameter(type) {
50627             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50628         }
50629         function isNonDeferredTypeReference(type) {
50630             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50631         }
50632         function isTypeReferenceWithGenericArguments(type) {
50633             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50634         }
50635         /**
50636          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50637          *   where A.id=111 and number.id=12
50638          */
50639         function getTypeReferenceId(type, typeParameters, depth) {
50640             if (depth === void 0) { depth = 0; }
50641             var result = "" + type.target.id;
50642             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50643                 var t = _a[_i];
50644                 if (isUnconstrainedTypeParameter(t)) {
50645                     var index = typeParameters.indexOf(t);
50646                     if (index < 0) {
50647                         index = typeParameters.length;
50648                         typeParameters.push(t);
50649                     }
50650                     result += "=" + index;
50651                 }
50652                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50653                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50654                 }
50655                 else {
50656                     result += "-" + t.id;
50657                 }
50658             }
50659             return result;
50660         }
50661         /**
50662          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50663          * For other cases, the types ids are used.
50664          */
50665         function getRelationKey(source, target, intersectionState, relation) {
50666             if (relation === identityRelation && source.id > target.id) {
50667                 var temp = source;
50668                 source = target;
50669                 target = temp;
50670             }
50671             var postFix = intersectionState ? ":" + intersectionState : "";
50672             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50673                 var typeParameters = [];
50674                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50675             }
50676             return source.id + "," + target.id + postFix;
50677         }
50678         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50679         // value that isn't undefined.
50680         function forEachProperty(prop, callback) {
50681             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50682                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50683                     var t = _a[_i];
50684                     var p = getPropertyOfType(t, prop.escapedName);
50685                     var result = p && forEachProperty(p, callback);
50686                     if (result) {
50687                         return result;
50688                     }
50689                 }
50690                 return undefined;
50691             }
50692             return callback(prop);
50693         }
50694         // Return the declaring class type of a property or undefined if property not declared in class
50695         function getDeclaringClass(prop) {
50696             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50697         }
50698         // Return true if some underlying source property is declared in a class that derives
50699         // from the given base class.
50700         function isPropertyInClassDerivedFrom(prop, baseClass) {
50701             return forEachProperty(prop, function (sp) {
50702                 var sourceClass = getDeclaringClass(sp);
50703                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50704             });
50705         }
50706         // Return true if source property is a valid override of protected parts of target property.
50707         function isValidOverrideOf(sourceProp, targetProp) {
50708             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50709                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50710         }
50711         // Return true if the given class derives from each of the declaring classes of the protected
50712         // constituents of the given property.
50713         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50714             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50715                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50716         }
50717         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50718         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50719         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50720         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50721         // levels, but unequal at some level beyond that.
50722         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50723         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50724         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50725         function isDeeplyNestedType(type, stack, depth) {
50726             // We track all object types that have an associated symbol (representing the origin of the type)
50727             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50728                 var symbol = type.symbol;
50729                 if (symbol) {
50730                     var count = 0;
50731                     for (var i = 0; i < depth; i++) {
50732                         var t = stack[i];
50733                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50734                             count++;
50735                             if (count >= 5)
50736                                 return true;
50737                         }
50738                     }
50739                 }
50740             }
50741             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50742                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50743                 var count = 0;
50744                 for (var i = 0; i < depth; i++) {
50745                     var t = stack[i];
50746                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50747                         count++;
50748                         if (count >= 5)
50749                             return true;
50750                     }
50751                 }
50752             }
50753             return false;
50754         }
50755         /**
50756          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50757          */
50758         function getRootObjectTypeFromIndexedAccessChain(type) {
50759             var t = type;
50760             while (t.flags & 8388608 /* IndexedAccess */) {
50761                 t = t.objectType;
50762             }
50763             return t;
50764         }
50765         function isPropertyIdenticalTo(sourceProp, targetProp) {
50766             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50767         }
50768         function compareProperties(sourceProp, targetProp, compareTypes) {
50769             // Two members are considered identical when
50770             // - they are public properties with identical names, optionality, and types,
50771             // - they are private or protected properties originating in the same declaration and having identical types
50772             if (sourceProp === targetProp) {
50773                 return -1 /* True */;
50774             }
50775             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50776             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50777             if (sourcePropAccessibility !== targetPropAccessibility) {
50778                 return 0 /* False */;
50779             }
50780             if (sourcePropAccessibility) {
50781                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50782                     return 0 /* False */;
50783                 }
50784             }
50785             else {
50786                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50787                     return 0 /* False */;
50788                 }
50789             }
50790             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50791                 return 0 /* False */;
50792             }
50793             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50794         }
50795         function isMatchingSignature(source, target, partialMatch) {
50796             var sourceParameterCount = getParameterCount(source);
50797             var targetParameterCount = getParameterCount(target);
50798             var sourceMinArgumentCount = getMinArgumentCount(source);
50799             var targetMinArgumentCount = getMinArgumentCount(target);
50800             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50801             var targetHasRestParameter = hasEffectiveRestParameter(target);
50802             // A source signature matches a target signature if the two signatures have the same number of required,
50803             // optional, and rest parameters.
50804             if (sourceParameterCount === targetParameterCount &&
50805                 sourceMinArgumentCount === targetMinArgumentCount &&
50806                 sourceHasRestParameter === targetHasRestParameter) {
50807                 return true;
50808             }
50809             // A source signature partially matches a target signature if the target signature has no fewer required
50810             // parameters
50811             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50812                 return true;
50813             }
50814             return false;
50815         }
50816         /**
50817          * See signatureRelatedTo, compareSignaturesIdentical
50818          */
50819         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50820             // TODO (drosen): De-duplicate code between related functions.
50821             if (source === target) {
50822                 return -1 /* True */;
50823             }
50824             if (!(isMatchingSignature(source, target, partialMatch))) {
50825                 return 0 /* False */;
50826             }
50827             // Check that the two signatures have the same number of type parameters.
50828             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
50829                 return 0 /* False */;
50830             }
50831             // Check that type parameter constraints and defaults match. If they do, instantiate the source
50832             // signature with the type parameters of the target signature and continue the comparison.
50833             if (target.typeParameters) {
50834                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
50835                 for (var i = 0; i < target.typeParameters.length; i++) {
50836                     var s = source.typeParameters[i];
50837                     var t = target.typeParameters[i];
50838                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
50839                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
50840                         return 0 /* False */;
50841                     }
50842                 }
50843                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
50844             }
50845             var result = -1 /* True */;
50846             if (!ignoreThisTypes) {
50847                 var sourceThisType = getThisTypeOfSignature(source);
50848                 if (sourceThisType) {
50849                     var targetThisType = getThisTypeOfSignature(target);
50850                     if (targetThisType) {
50851                         var related = compareTypes(sourceThisType, targetThisType);
50852                         if (!related) {
50853                             return 0 /* False */;
50854                         }
50855                         result &= related;
50856                     }
50857                 }
50858             }
50859             var targetLen = getParameterCount(target);
50860             for (var i = 0; i < targetLen; i++) {
50861                 var s = getTypeAtPosition(source, i);
50862                 var t = getTypeAtPosition(target, i);
50863                 var related = compareTypes(t, s);
50864                 if (!related) {
50865                     return 0 /* False */;
50866                 }
50867                 result &= related;
50868             }
50869             if (!ignoreReturnTypes) {
50870                 var sourceTypePredicate = getTypePredicateOfSignature(source);
50871                 var targetTypePredicate = getTypePredicateOfSignature(target);
50872                 result &= sourceTypePredicate || targetTypePredicate ?
50873                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
50874                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
50875             }
50876             return result;
50877         }
50878         function compareTypePredicatesIdentical(source, target, compareTypes) {
50879             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
50880                 source.type === target.type ? -1 /* True */ :
50881                     source.type && target.type ? compareTypes(source.type, target.type) :
50882                         0 /* False */;
50883         }
50884         function literalTypesWithSameBaseType(types) {
50885             var commonBaseType;
50886             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
50887                 var t = types_12[_i];
50888                 var baseType = getBaseTypeOfLiteralType(t);
50889                 if (!commonBaseType) {
50890                     commonBaseType = baseType;
50891                 }
50892                 if (baseType === t || baseType !== commonBaseType) {
50893                     return false;
50894                 }
50895             }
50896             return true;
50897         }
50898         // When the candidate types are all literal types with the same base type, return a union
50899         // of those literal types. Otherwise, return the leftmost type for which no type to the
50900         // right is a supertype.
50901         function getSupertypeOrUnion(types) {
50902             return literalTypesWithSameBaseType(types) ?
50903                 getUnionType(types) :
50904                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
50905         }
50906         function getCommonSupertype(types) {
50907             if (!strictNullChecks) {
50908                 return getSupertypeOrUnion(types);
50909             }
50910             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
50911             return primaryTypes.length ?
50912                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
50913                 getUnionType(types, 2 /* Subtype */);
50914         }
50915         // Return the leftmost type for which no type to the right is a subtype.
50916         function getCommonSubtype(types) {
50917             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
50918         }
50919         function isArrayType(type) {
50920             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
50921         }
50922         function isReadonlyArrayType(type) {
50923             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
50924         }
50925         function isMutableArrayOrTuple(type) {
50926             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
50927         }
50928         function getElementTypeOfArrayType(type) {
50929             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50930         }
50931         function isArrayLikeType(type) {
50932             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
50933             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
50934             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
50935         }
50936         function isEmptyArrayLiteralType(type) {
50937             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50938             return elementType === undefinedWideningType || elementType === implicitNeverType;
50939         }
50940         function isTupleLikeType(type) {
50941             return isTupleType(type) || !!getPropertyOfType(type, "0");
50942         }
50943         function isArrayOrTupleLikeType(type) {
50944             return isArrayLikeType(type) || isTupleLikeType(type);
50945         }
50946         function getTupleElementType(type, index) {
50947             var propType = getTypeOfPropertyOfType(type, "" + index);
50948             if (propType) {
50949                 return propType;
50950             }
50951             if (everyType(type, isTupleType)) {
50952                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
50953             }
50954             return undefined;
50955         }
50956         function isNeitherUnitTypeNorNever(type) {
50957             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
50958         }
50959         function isUnitType(type) {
50960             return !!(type.flags & 109440 /* Unit */);
50961         }
50962         function isLiteralType(type) {
50963             return type.flags & 16 /* Boolean */ ? true :
50964                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
50965                     isUnitType(type);
50966         }
50967         function getBaseTypeOfLiteralType(type) {
50968             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
50969                 type.flags & 128 /* StringLiteral */ ? stringType :
50970                     type.flags & 256 /* NumberLiteral */ ? numberType :
50971                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
50972                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
50973                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
50974                                     type;
50975         }
50976         function getWidenedLiteralType(type) {
50977             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
50978                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
50979                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
50980                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
50981                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
50982                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
50983                                     type;
50984         }
50985         function getWidenedUniqueESSymbolType(type) {
50986             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
50987                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
50988                     type;
50989         }
50990         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
50991             if (!isLiteralOfContextualType(type, contextualType)) {
50992                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
50993             }
50994             return type;
50995         }
50996         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
50997             if (type && isUnitType(type)) {
50998                 var contextualType = !contextualSignatureReturnType ? undefined :
50999                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51000                         contextualSignatureReturnType;
51001                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51002             }
51003             return type;
51004         }
51005         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51006             if (type && isUnitType(type)) {
51007                 var contextualType = !contextualSignatureReturnType ? undefined :
51008                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51009                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51010             }
51011             return type;
51012         }
51013         /**
51014          * Check if a Type was written as a tuple type literal.
51015          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51016          */
51017         function isTupleType(type) {
51018             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51019         }
51020         function getRestTypeOfTupleType(type) {
51021             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51022         }
51023         function getRestArrayTypeOfTupleType(type) {
51024             var restType = getRestTypeOfTupleType(type);
51025             return restType && createArrayType(restType);
51026         }
51027         function getLengthOfTupleType(type) {
51028             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51029         }
51030         function isZeroBigInt(_a) {
51031             var value = _a.value;
51032             return value.base10Value === "0";
51033         }
51034         function getFalsyFlagsOfTypes(types) {
51035             var result = 0;
51036             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51037                 var t = types_13[_i];
51038                 result |= getFalsyFlags(t);
51039             }
51040             return result;
51041         }
51042         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51043         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51044         // no flags for all other types (including non-falsy literal types).
51045         function getFalsyFlags(type) {
51046             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51047                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51048                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51049                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51050                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51051                                 type.flags & 117724 /* PossiblyFalsy */;
51052         }
51053         function removeDefinitelyFalsyTypes(type) {
51054             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51055                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51056                 type;
51057         }
51058         function extractDefinitelyFalsyTypes(type) {
51059             return mapType(type, getDefinitelyFalsyPartOfType);
51060         }
51061         function getDefinitelyFalsyPartOfType(type) {
51062             return type.flags & 4 /* String */ ? emptyStringType :
51063                 type.flags & 8 /* Number */ ? zeroType :
51064                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51065                         type === regularFalseType ||
51066                             type === falseType ||
51067                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51068                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51069                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51070                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51071                             neverType;
51072         }
51073         /**
51074          * Add undefined or null or both to a type if they are missing.
51075          * @param type - type to add undefined and/or null to if not present
51076          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51077          */
51078         function getNullableType(type, flags) {
51079             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51080             return missing === 0 ? type :
51081                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51082                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51083                         getUnionType([type, undefinedType, nullType]);
51084         }
51085         function getOptionalType(type) {
51086             ts.Debug.assert(strictNullChecks);
51087             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51088         }
51089         function getGlobalNonNullableTypeInstantiation(type) {
51090             if (!deferredGlobalNonNullableTypeAlias) {
51091                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51092             }
51093             // Use NonNullable global type alias if available to improve quick info/declaration emit
51094             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51095                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51096             }
51097             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51098         }
51099         function getNonNullableType(type) {
51100             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51101         }
51102         function addOptionalTypeMarker(type) {
51103             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51104         }
51105         function isNotOptionalTypeMarker(type) {
51106             return type !== optionalType;
51107         }
51108         function removeOptionalTypeMarker(type) {
51109             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51110         }
51111         function propagateOptionalTypeMarker(type, node, wasOptional) {
51112             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51113         }
51114         function getOptionalExpressionType(exprType, expression) {
51115             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51116                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51117                     exprType;
51118         }
51119         /**
51120          * Is source potentially coercible to target type under `==`.
51121          * Assumes that `source` is a constituent of a union, hence
51122          * the boolean literal flag on the LHS, but not on the RHS.
51123          *
51124          * This does not fully replicate the semantics of `==`. The
51125          * intention is to catch cases that are clearly not right.
51126          *
51127          * Comparing (string | number) to number should not remove the
51128          * string element.
51129          *
51130          * Comparing (string | number) to 1 will remove the string
51131          * element, though this is not sound. This is a pragmatic
51132          * choice.
51133          *
51134          * @see narrowTypeByEquality
51135          *
51136          * @param source
51137          * @param target
51138          */
51139         function isCoercibleUnderDoubleEquals(source, target) {
51140             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51141                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51142         }
51143         /**
51144          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51145          * with no call or construct signatures.
51146          */
51147         function isObjectTypeWithInferableIndex(type) {
51148             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51149                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51150                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51151         }
51152         function createSymbolWithType(source, type) {
51153             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51154             symbol.declarations = source.declarations;
51155             symbol.parent = source.parent;
51156             symbol.type = type;
51157             symbol.target = source;
51158             if (source.valueDeclaration) {
51159                 symbol.valueDeclaration = source.valueDeclaration;
51160             }
51161             var nameType = getSymbolLinks(source).nameType;
51162             if (nameType) {
51163                 symbol.nameType = nameType;
51164             }
51165             return symbol;
51166         }
51167         function transformTypeOfMembers(type, f) {
51168             var members = ts.createSymbolTable();
51169             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51170                 var property = _a[_i];
51171                 var original = getTypeOfSymbol(property);
51172                 var updated = f(original);
51173                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51174             }
51175             return members;
51176         }
51177         /**
51178          * If the the provided object literal is subject to the excess properties check,
51179          * create a new that is exempt. Recursively mark object literal members as exempt.
51180          * Leave signatures alone since they are not subject to the check.
51181          */
51182         function getRegularTypeOfObjectLiteral(type) {
51183             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51184                 return type;
51185             }
51186             var regularType = type.regularType;
51187             if (regularType) {
51188                 return regularType;
51189             }
51190             var resolved = type;
51191             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51192             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51193             regularNew.flags = resolved.flags;
51194             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51195             type.regularType = regularNew;
51196             return regularNew;
51197         }
51198         function createWideningContext(parent, propertyName, siblings) {
51199             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51200         }
51201         function getSiblingsOfContext(context) {
51202             if (!context.siblings) {
51203                 var siblings_1 = [];
51204                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51205                     var type = _a[_i];
51206                     if (isObjectLiteralType(type)) {
51207                         var prop = getPropertyOfObjectType(type, context.propertyName);
51208                         if (prop) {
51209                             forEachType(getTypeOfSymbol(prop), function (t) {
51210                                 siblings_1.push(t);
51211                             });
51212                         }
51213                     }
51214                 }
51215                 context.siblings = siblings_1;
51216             }
51217             return context.siblings;
51218         }
51219         function getPropertiesOfContext(context) {
51220             if (!context.resolvedProperties) {
51221                 var names = ts.createMap();
51222                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51223                     var t = _a[_i];
51224                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51225                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51226                             var prop = _c[_b];
51227                             names.set(prop.escapedName, prop);
51228                         }
51229                     }
51230                 }
51231                 context.resolvedProperties = ts.arrayFrom(names.values());
51232             }
51233             return context.resolvedProperties;
51234         }
51235         function getWidenedProperty(prop, context) {
51236             if (!(prop.flags & 4 /* Property */)) {
51237                 // Since get accessors already widen their return value there is no need to
51238                 // widen accessor based properties here.
51239                 return prop;
51240             }
51241             var original = getTypeOfSymbol(prop);
51242             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51243             var widened = getWidenedTypeWithContext(original, propContext);
51244             return widened === original ? prop : createSymbolWithType(prop, widened);
51245         }
51246         function getUndefinedProperty(prop) {
51247             var cached = undefinedProperties.get(prop.escapedName);
51248             if (cached) {
51249                 return cached;
51250             }
51251             var result = createSymbolWithType(prop, undefinedType);
51252             result.flags |= 16777216 /* Optional */;
51253             undefinedProperties.set(prop.escapedName, result);
51254             return result;
51255         }
51256         function getWidenedTypeOfObjectLiteral(type, context) {
51257             var members = ts.createSymbolTable();
51258             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51259                 var prop = _a[_i];
51260                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51261             }
51262             if (context) {
51263                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51264                     var prop = _c[_b];
51265                     if (!members.has(prop.escapedName)) {
51266                         members.set(prop.escapedName, getUndefinedProperty(prop));
51267                     }
51268                 }
51269             }
51270             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51271             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51272             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51273             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51274             return result;
51275         }
51276         function getWidenedType(type) {
51277             return getWidenedTypeWithContext(type, /*context*/ undefined);
51278         }
51279         function getWidenedTypeWithContext(type, context) {
51280             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51281                 if (context === undefined && type.widened) {
51282                     return type.widened;
51283                 }
51284                 var result = void 0;
51285                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51286                     result = anyType;
51287                 }
51288                 else if (isObjectLiteralType(type)) {
51289                     result = getWidenedTypeOfObjectLiteral(type, context);
51290                 }
51291                 else if (type.flags & 1048576 /* Union */) {
51292                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51293                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51294                     // Widening an empty object literal transitions from a highly restrictive type to
51295                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51296                     // union includes empty object types (e.g. reducing {} | string to just {}).
51297                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51298                 }
51299                 else if (type.flags & 2097152 /* Intersection */) {
51300                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51301                 }
51302                 else if (isArrayType(type) || isTupleType(type)) {
51303                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51304                 }
51305                 if (result && context === undefined) {
51306                     type.widened = result;
51307                 }
51308                 return result || type;
51309             }
51310             return type;
51311         }
51312         /**
51313          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51314          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51315          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51316          * (type argument inference is an example).
51317          *
51318          * The return value indicates whether an error was in fact reported. The particular circumstances
51319          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51320          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51321          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51322          */
51323         function reportWideningErrorsInType(type) {
51324             var errorReported = false;
51325             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51326                 if (type.flags & 1048576 /* Union */) {
51327                     if (ts.some(type.types, isEmptyObjectType)) {
51328                         errorReported = true;
51329                     }
51330                     else {
51331                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51332                             var t = _a[_i];
51333                             if (reportWideningErrorsInType(t)) {
51334                                 errorReported = true;
51335                             }
51336                         }
51337                     }
51338                 }
51339                 if (isArrayType(type) || isTupleType(type)) {
51340                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51341                         var t = _c[_b];
51342                         if (reportWideningErrorsInType(t)) {
51343                             errorReported = true;
51344                         }
51345                     }
51346                 }
51347                 if (isObjectLiteralType(type)) {
51348                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51349                         var p = _e[_d];
51350                         var t = getTypeOfSymbol(p);
51351                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51352                             if (!reportWideningErrorsInType(t)) {
51353                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51354                             }
51355                             errorReported = true;
51356                         }
51357                     }
51358                 }
51359             }
51360             return errorReported;
51361         }
51362         function reportImplicitAny(declaration, type, wideningKind) {
51363             var typeAsString = typeToString(getWidenedType(type));
51364             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51365                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51366                 return;
51367             }
51368             var diagnostic;
51369             switch (declaration.kind) {
51370                 case 209 /* BinaryExpression */:
51371                 case 159 /* PropertyDeclaration */:
51372                 case 158 /* PropertySignature */:
51373                     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;
51374                     break;
51375                 case 156 /* Parameter */:
51376                     var param = declaration;
51377                     if (ts.isIdentifier(param.name) &&
51378                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51379                         param.parent.parameters.indexOf(param) > -1 &&
51380                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51381                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51382                         var newName = "arg" + param.parent.parameters.indexOf(param);
51383                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51384                         return;
51385                     }
51386                     diagnostic = declaration.dotDotDotToken ?
51387                         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 :
51388                         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;
51389                     break;
51390                 case 191 /* BindingElement */:
51391                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51392                     if (!noImplicitAny) {
51393                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51394                         return;
51395                     }
51396                     break;
51397                 case 300 /* JSDocFunctionType */:
51398                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51399                     return;
51400                 case 244 /* FunctionDeclaration */:
51401                 case 161 /* MethodDeclaration */:
51402                 case 160 /* MethodSignature */:
51403                 case 163 /* GetAccessor */:
51404                 case 164 /* SetAccessor */:
51405                 case 201 /* FunctionExpression */:
51406                 case 202 /* ArrowFunction */:
51407                     if (noImplicitAny && !declaration.name) {
51408                         if (wideningKind === 3 /* GeneratorYield */) {
51409                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51410                         }
51411                         else {
51412                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51413                         }
51414                         return;
51415                     }
51416                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51417                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51418                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51419                     break;
51420                 case 186 /* MappedType */:
51421                     if (noImplicitAny) {
51422                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51423                     }
51424                     return;
51425                 default:
51426                     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;
51427             }
51428             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51429         }
51430         function reportErrorsFromWidening(declaration, type, wideningKind) {
51431             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51432                 // Report implicit any error within type if possible, otherwise report error on declaration
51433                 if (!reportWideningErrorsInType(type)) {
51434                     reportImplicitAny(declaration, type, wideningKind);
51435                 }
51436             }
51437         }
51438         function applyToParameterTypes(source, target, callback) {
51439             var sourceCount = getParameterCount(source);
51440             var targetCount = getParameterCount(target);
51441             var sourceRestType = getEffectiveRestType(source);
51442             var targetRestType = getEffectiveRestType(target);
51443             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51444             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51445             var sourceThisType = getThisTypeOfSignature(source);
51446             if (sourceThisType) {
51447                 var targetThisType = getThisTypeOfSignature(target);
51448                 if (targetThisType) {
51449                     callback(sourceThisType, targetThisType);
51450                 }
51451             }
51452             for (var i = 0; i < paramCount; i++) {
51453                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51454             }
51455             if (targetRestType) {
51456                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51457             }
51458         }
51459         function applyToReturnTypes(source, target, callback) {
51460             var sourceTypePredicate = getTypePredicateOfSignature(source);
51461             var targetTypePredicate = getTypePredicateOfSignature(target);
51462             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51463                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51464             }
51465             else {
51466                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51467             }
51468         }
51469         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51470             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51471         }
51472         function cloneInferenceContext(context, extraFlags) {
51473             if (extraFlags === void 0) { extraFlags = 0; }
51474             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51475         }
51476         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51477             var context = {
51478                 inferences: inferences,
51479                 signature: signature,
51480                 flags: flags,
51481                 compareTypes: compareTypes,
51482                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51483                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51484             };
51485             return context;
51486         }
51487         function mapToInferredType(context, t, fix) {
51488             var inferences = context.inferences;
51489             for (var i = 0; i < inferences.length; i++) {
51490                 var inference = inferences[i];
51491                 if (t === inference.typeParameter) {
51492                     if (fix && !inference.isFixed) {
51493                         clearCachedInferences(inferences);
51494                         inference.isFixed = true;
51495                     }
51496                     return getInferredType(context, i);
51497                 }
51498             }
51499             return t;
51500         }
51501         function clearCachedInferences(inferences) {
51502             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51503                 var inference = inferences_1[_i];
51504                 if (!inference.isFixed) {
51505                     inference.inferredType = undefined;
51506                 }
51507             }
51508         }
51509         function createInferenceInfo(typeParameter) {
51510             return {
51511                 typeParameter: typeParameter,
51512                 candidates: undefined,
51513                 contraCandidates: undefined,
51514                 inferredType: undefined,
51515                 priority: undefined,
51516                 topLevel: true,
51517                 isFixed: false
51518             };
51519         }
51520         function cloneInferenceInfo(inference) {
51521             return {
51522                 typeParameter: inference.typeParameter,
51523                 candidates: inference.candidates && inference.candidates.slice(),
51524                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51525                 inferredType: inference.inferredType,
51526                 priority: inference.priority,
51527                 topLevel: inference.topLevel,
51528                 isFixed: inference.isFixed
51529             };
51530         }
51531         function cloneInferredPartOfContext(context) {
51532             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51533             return inferences.length ?
51534                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51535                 undefined;
51536         }
51537         function getMapperFromContext(context) {
51538             return context && context.mapper;
51539         }
51540         // Return true if the given type could possibly reference a type parameter for which
51541         // we perform type inference (i.e. a type parameter of a generic function). We cache
51542         // results for union and intersection types for performance reasons.
51543         function couldContainTypeVariables(type) {
51544             var objectFlags = ts.getObjectFlags(type);
51545             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51546                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51547             }
51548             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51549                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51550                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51551                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51552                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51553             if (type.flags & 3899393 /* ObjectFlagsType */) {
51554                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51555             }
51556             return result;
51557         }
51558         function isTypeParameterAtTopLevel(type, typeParameter) {
51559             return !!(type === typeParameter ||
51560                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51561                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51562                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51563         }
51564         /** Create an object with properties named in the string literal type. Every property has type `any` */
51565         function createEmptyObjectTypeFromStringLiteral(type) {
51566             var members = ts.createSymbolTable();
51567             forEachType(type, function (t) {
51568                 if (!(t.flags & 128 /* StringLiteral */)) {
51569                     return;
51570                 }
51571                 var name = ts.escapeLeadingUnderscores(t.value);
51572                 var literalProp = createSymbol(4 /* Property */, name);
51573                 literalProp.type = anyType;
51574                 if (t.symbol) {
51575                     literalProp.declarations = t.symbol.declarations;
51576                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51577                 }
51578                 members.set(name, literalProp);
51579             });
51580             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51581             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51582         }
51583         /**
51584          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51585          * an object type with the same set of properties as the source type, where the type of each
51586          * property is computed by inferring from the source property type to X for the type
51587          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51588          */
51589         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51590             var key = source.id + "," + target.id + "," + constraint.id;
51591             if (reverseMappedCache.has(key)) {
51592                 return reverseMappedCache.get(key);
51593             }
51594             reverseMappedCache.set(key, undefined);
51595             var type = createReverseMappedType(source, target, constraint);
51596             reverseMappedCache.set(key, type);
51597             return type;
51598         }
51599         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51600         // an object literal type with at least one property of an inferable type. For example, an object
51601         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51602         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51603         function isPartiallyInferableType(type) {
51604             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51605                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51606         }
51607         function createReverseMappedType(source, target, constraint) {
51608             // We consider a source type reverse mappable if it has a string index signature or if
51609             // it has one or more properties and is of a partially inferable type.
51610             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51611                 return undefined;
51612             }
51613             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51614             // applied to the element type(s).
51615             if (isArrayType(source)) {
51616                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51617             }
51618             if (isTupleType(source)) {
51619                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51620                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51621                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51622                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51623             }
51624             // For all other object types we infer a new object type where the reverse mapping has been
51625             // applied to the type of each property.
51626             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51627             reversed.source = source;
51628             reversed.mappedType = target;
51629             reversed.constraintType = constraint;
51630             return reversed;
51631         }
51632         function getTypeOfReverseMappedSymbol(symbol) {
51633             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51634         }
51635         function inferReverseMappedType(sourceType, target, constraint) {
51636             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51637             var templateType = getTemplateTypeFromMappedType(target);
51638             var inference = createInferenceInfo(typeParameter);
51639             inferTypes([inference], sourceType, templateType);
51640             return getTypeFromInference(inference) || unknownType;
51641         }
51642         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51643             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51644             return __generator(this, function (_a) {
51645                 switch (_a.label) {
51646                     case 0:
51647                         properties = getPropertiesOfType(target);
51648                         _i = 0, properties_2 = properties;
51649                         _a.label = 1;
51650                     case 1:
51651                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51652                         targetProp = properties_2[_i];
51653                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51654                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51655                             return [3 /*break*/, 5];
51656                         }
51657                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51658                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51659                         if (!!sourceProp) return [3 /*break*/, 3];
51660                         return [4 /*yield*/, targetProp];
51661                     case 2:
51662                         _a.sent();
51663                         return [3 /*break*/, 5];
51664                     case 3:
51665                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51666                         targetType = getTypeOfSymbol(targetProp);
51667                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51668                         sourceType = getTypeOfSymbol(sourceProp);
51669                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51670                         return [4 /*yield*/, targetProp];
51671                     case 4:
51672                         _a.sent();
51673                         _a.label = 5;
51674                     case 5:
51675                         _i++;
51676                         return [3 /*break*/, 1];
51677                     case 6: return [2 /*return*/];
51678                 }
51679             });
51680         }
51681         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51682             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51683             if (!result.done)
51684                 return result.value;
51685         }
51686         function tupleTypesDefinitelyUnrelated(source, target) {
51687             return target.target.minLength > source.target.minLength ||
51688                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51689         }
51690         function typesDefinitelyUnrelated(source, target) {
51691             // Two tuple types with incompatible arities are definitely unrelated.
51692             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51693             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51694                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51695                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51696         }
51697         function getTypeFromInference(inference) {
51698             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51699                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51700                     undefined;
51701         }
51702         function hasSkipDirectInferenceFlag(node) {
51703             return !!getNodeLinks(node).skipDirectInference;
51704         }
51705         function isFromInferenceBlockedSource(type) {
51706             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51707         }
51708         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51709             if (priority === void 0) { priority = 0; }
51710             if (contravariant === void 0) { contravariant = false; }
51711             var symbolOrTypeStack;
51712             var visited;
51713             var bivariant = false;
51714             var propagationType;
51715             var inferencePriority = 512 /* MaxValue */;
51716             var allowComplexConstraintInference = true;
51717             inferFromTypes(originalSource, originalTarget);
51718             function inferFromTypes(source, target) {
51719                 if (!couldContainTypeVariables(target)) {
51720                     return;
51721                 }
51722                 if (source === wildcardType) {
51723                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51724                     // referenced in the target type, so we record it as the propagation type and infer from the
51725                     // target to itself. Then, as we find candidates we substitute the propagation type.
51726                     var savePropagationType = propagationType;
51727                     propagationType = source;
51728                     inferFromTypes(target, target);
51729                     propagationType = savePropagationType;
51730                     return;
51731                 }
51732                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51733                     // Source and target are types originating in the same generic type alias declaration.
51734                     // Simply infer from source type arguments to target type arguments.
51735                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51736                     return;
51737                 }
51738                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51739                     // When source and target are the same union or intersection type, just relate each constituent
51740                     // type to itself.
51741                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51742                         var t = _a[_i];
51743                         inferFromTypes(t, t);
51744                     }
51745                     return;
51746                 }
51747                 if (target.flags & 1048576 /* Union */) {
51748                     // First, infer between identically matching source and target constituents and remove the
51749                     // matching types.
51750                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51751                     // Next, infer between closely matching source and target constituents and remove
51752                     // the matching types. Types closely match when they are instantiations of the same
51753                     // object type or instantiations of the same type alias.
51754                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51755                     if (targets.length === 0) {
51756                         return;
51757                     }
51758                     target = getUnionType(targets);
51759                     if (sources.length === 0) {
51760                         // All source constituents have been matched and there is nothing further to infer from.
51761                         // However, simply making no inferences is undesirable because it could ultimately mean
51762                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51763                         // the full source to whatever remains in the target. For example, when inferring from
51764                         // string to 'string | T', make a lower priority inference of string for T.
51765                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51766                         return;
51767                     }
51768                     source = getUnionType(sources);
51769                 }
51770                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51771                     // We reduce intersection types only when they contain naked type parameters. For example, when
51772                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51773                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51774                     // string[] on the source side and infer string for T.
51775                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51776                     // in such scenarios.
51777                     if (!(source.flags & 1048576 /* Union */)) {
51778                         // Infer between identically matching source and target constituents and remove the matching types.
51779                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51780                         if (sources.length === 0 || targets.length === 0) {
51781                             return;
51782                         }
51783                         source = getIntersectionType(sources);
51784                         target = getIntersectionType(targets);
51785                     }
51786                 }
51787                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51788                     target = getActualTypeVariable(target);
51789                 }
51790                 if (target.flags & 8650752 /* TypeVariable */) {
51791                     // If target is a type parameter, make an inference, unless the source type contains
51792                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51793                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51794                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51795                     // not contain anyFunctionType when we come back to this argument for its second round
51796                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51797                     // when constructing types from type parameters that had no inference candidates).
51798                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51799                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51800                         return;
51801                     }
51802                     var inference = getInferenceInfoForType(target);
51803                     if (inference) {
51804                         if (!inference.isFixed) {
51805                             if (inference.priority === undefined || priority < inference.priority) {
51806                                 inference.candidates = undefined;
51807                                 inference.contraCandidates = undefined;
51808                                 inference.topLevel = true;
51809                                 inference.priority = priority;
51810                             }
51811                             if (priority === inference.priority) {
51812                                 var candidate = propagationType || source;
51813                                 // We make contravariant inferences only if we are in a pure contravariant position,
51814                                 // i.e. only if we have not descended into a bivariant position.
51815                                 if (contravariant && !bivariant) {
51816                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51817                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51818                                         clearCachedInferences(inferences);
51819                                     }
51820                                 }
51821                                 else if (!ts.contains(inference.candidates, candidate)) {
51822                                     inference.candidates = ts.append(inference.candidates, candidate);
51823                                     clearCachedInferences(inferences);
51824                                 }
51825                             }
51826                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
51827                                 inference.topLevel = false;
51828                                 clearCachedInferences(inferences);
51829                             }
51830                         }
51831                         inferencePriority = Math.min(inferencePriority, priority);
51832                         return;
51833                     }
51834                     else {
51835                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
51836                         var simplified = getSimplifiedType(target, /*writing*/ false);
51837                         if (simplified !== target) {
51838                             invokeOnce(source, simplified, inferFromTypes);
51839                         }
51840                         else if (target.flags & 8388608 /* IndexedAccess */) {
51841                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
51842                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
51843                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
51844                             if (indexType.flags & 63176704 /* Instantiable */) {
51845                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
51846                                 if (simplified_1 && simplified_1 !== target) {
51847                                     invokeOnce(source, simplified_1, inferFromTypes);
51848                                 }
51849                             }
51850                         }
51851                     }
51852                 }
51853                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
51854                     !(source.node && target.node)) {
51855                     // If source and target are references to the same generic type, infer from type arguments
51856                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
51857                 }
51858                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
51859                     contravariant = !contravariant;
51860                     inferFromTypes(source.type, target.type);
51861                     contravariant = !contravariant;
51862                 }
51863                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
51864                     var empty = createEmptyObjectTypeFromStringLiteral(source);
51865                     contravariant = !contravariant;
51866                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
51867                     contravariant = !contravariant;
51868                 }
51869                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
51870                     inferFromTypes(source.objectType, target.objectType);
51871                     inferFromTypes(source.indexType, target.indexType);
51872                 }
51873                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
51874                     inferFromTypes(source.checkType, target.checkType);
51875                     inferFromTypes(source.extendsType, target.extendsType);
51876                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
51877                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
51878                 }
51879                 else if (target.flags & 16777216 /* Conditional */) {
51880                     var savePriority = priority;
51881                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
51882                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
51883                     inferToMultipleTypes(source, targetTypes, target.flags);
51884                     priority = savePriority;
51885                 }
51886                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
51887                     inferToMultipleTypes(source, target.types, target.flags);
51888                 }
51889                 else if (source.flags & 1048576 /* Union */) {
51890                     // Source is a union or intersection type, infer from each constituent type
51891                     var sourceTypes = source.types;
51892                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
51893                         var sourceType = sourceTypes_2[_e];
51894                         inferFromTypes(sourceType, target);
51895                     }
51896                 }
51897                 else {
51898                     source = getReducedType(source);
51899                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
51900                         var apparentSource = getApparentType(source);
51901                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
51902                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
51903                         // with the simplified source.
51904                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
51905                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
51906                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
51907                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
51908                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
51909                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
51910                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
51911                             // remove this `allowComplexConstraintInference` flag.
51912                             allowComplexConstraintInference = false;
51913                             return inferFromTypes(apparentSource, target);
51914                         }
51915                         source = apparentSource;
51916                     }
51917                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51918                         invokeOnce(source, target, inferFromObjectTypes);
51919                     }
51920                 }
51921                 if (source.flags & 25165824 /* Simplifiable */) {
51922                     var simplified = getSimplifiedType(source, contravariant);
51923                     if (simplified !== source) {
51924                         inferFromTypes(simplified, target);
51925                     }
51926                 }
51927             }
51928             function inferWithPriority(source, target, newPriority) {
51929                 var savePriority = priority;
51930                 priority |= newPriority;
51931                 inferFromTypes(source, target);
51932                 priority = savePriority;
51933             }
51934             function invokeOnce(source, target, action) {
51935                 var key = source.id + "," + target.id;
51936                 var status = visited && visited.get(key);
51937                 if (status !== undefined) {
51938                     inferencePriority = Math.min(inferencePriority, status);
51939                     return;
51940                 }
51941                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
51942                 var saveInferencePriority = inferencePriority;
51943                 inferencePriority = 512 /* MaxValue */;
51944                 action(source, target);
51945                 visited.set(key, inferencePriority);
51946                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
51947             }
51948             function inferFromMatchingTypes(sources, targets, matches) {
51949                 var matchedSources;
51950                 var matchedTargets;
51951                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
51952                     var t = targets_1[_i];
51953                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
51954                         var s = sources_1[_a];
51955                         if (matches(s, t)) {
51956                             inferFromTypes(s, t);
51957                             matchedSources = ts.appendIfUnique(matchedSources, s);
51958                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
51959                         }
51960                     }
51961                 }
51962                 return [
51963                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
51964                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
51965                 ];
51966             }
51967             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
51968                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
51969                 for (var i = 0; i < count; i++) {
51970                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
51971                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
51972                     }
51973                     else {
51974                         inferFromTypes(sourceTypes[i], targetTypes[i]);
51975                     }
51976                 }
51977             }
51978             function inferFromContravariantTypes(source, target) {
51979                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
51980                     contravariant = !contravariant;
51981                     inferFromTypes(source, target);
51982                     contravariant = !contravariant;
51983                 }
51984                 else {
51985                     inferFromTypes(source, target);
51986                 }
51987             }
51988             function getInferenceInfoForType(type) {
51989                 if (type.flags & 8650752 /* TypeVariable */) {
51990                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
51991                         var inference = inferences_2[_i];
51992                         if (type === inference.typeParameter) {
51993                             return inference;
51994                         }
51995                     }
51996                 }
51997                 return undefined;
51998             }
51999             function getSingleTypeVariableFromIntersectionTypes(types) {
52000                 var typeVariable;
52001                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52002                     var type = types_14[_i];
52003                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52004                     if (!t || typeVariable && t !== typeVariable) {
52005                         return undefined;
52006                     }
52007                     typeVariable = t;
52008                 }
52009                 return typeVariable;
52010             }
52011             function inferToMultipleTypes(source, targets, targetFlags) {
52012                 var typeVariableCount = 0;
52013                 if (targetFlags & 1048576 /* Union */) {
52014                     var nakedTypeVariable = void 0;
52015                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52016                     var matched_1 = new Array(sources.length);
52017                     var inferenceCircularity = false;
52018                     // First infer to types that are not naked type variables. For each source type we
52019                     // track whether inferences were made from that particular type to some target with
52020                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52021                     // parameter.
52022                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52023                         var t = targets_2[_i];
52024                         if (getInferenceInfoForType(t)) {
52025                             nakedTypeVariable = t;
52026                             typeVariableCount++;
52027                         }
52028                         else {
52029                             for (var i = 0; i < sources.length; i++) {
52030                                 var saveInferencePriority = inferencePriority;
52031                                 inferencePriority = 512 /* MaxValue */;
52032                                 inferFromTypes(sources[i], t);
52033                                 if (inferencePriority === priority)
52034                                     matched_1[i] = true;
52035                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52036                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52037                             }
52038                         }
52039                     }
52040                     if (typeVariableCount === 0) {
52041                         // If every target is an intersection of types containing a single naked type variable,
52042                         // make a lower priority inference to that type variable. This handles inferring from
52043                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52044                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52045                         if (intersectionTypeVariable) {
52046                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52047                         }
52048                         return;
52049                     }
52050                     // If the target has a single naked type variable and no inference circularities were
52051                     // encountered above (meaning we explored the types fully), create a union of the source
52052                     // types from which no inferences have been made so far and infer from that union to the
52053                     // naked type variable.
52054                     if (typeVariableCount === 1 && !inferenceCircularity) {
52055                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52056                         if (unmatched.length) {
52057                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52058                             return;
52059                         }
52060                     }
52061                 }
52062                 else {
52063                     // We infer from types that are not naked type variables first so that inferences we
52064                     // make from nested naked type variables and given slightly higher priority by virtue
52065                     // of being first in the candidates array.
52066                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52067                         var t = targets_3[_a];
52068                         if (getInferenceInfoForType(t)) {
52069                             typeVariableCount++;
52070                         }
52071                         else {
52072                             inferFromTypes(source, t);
52073                         }
52074                     }
52075                 }
52076                 // Inferences directly to naked type variables are given lower priority as they are
52077                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52078                 // we want to infer string for T, not Promise<string> | string. For intersection types
52079                 // we only infer to single naked type variables.
52080                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52081                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52082                         var t = targets_4[_b];
52083                         if (getInferenceInfoForType(t)) {
52084                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52085                         }
52086                     }
52087                 }
52088             }
52089             function inferToMappedType(source, target, constraintType) {
52090                 if (constraintType.flags & 1048576 /* Union */) {
52091                     var result = false;
52092                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52093                         var type = _a[_i];
52094                         result = inferToMappedType(source, target, type) || result;
52095                     }
52096                     return result;
52097                 }
52098                 if (constraintType.flags & 4194304 /* Index */) {
52099                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52100                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52101                     // type and then make a secondary inference from that type to T. We make a secondary inference
52102                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52103                     var inference = getInferenceInfoForType(constraintType.type);
52104                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52105                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52106                         if (inferredType) {
52107                             // We assign a lower priority to inferences made from types containing non-inferrable
52108                             // types because we may only have a partial result (i.e. we may have failed to make
52109                             // reverse inferences for some properties).
52110                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52111                                 4 /* PartialHomomorphicMappedType */ :
52112                                 2 /* HomomorphicMappedType */);
52113                         }
52114                     }
52115                     return true;
52116                 }
52117                 if (constraintType.flags & 262144 /* TypeParameter */) {
52118                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52119                     // parameter. First infer from 'keyof S' to K.
52120                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52121                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52122                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52123                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52124                     // Pick<T, K>.
52125                     var extendedConstraint = getConstraintOfType(constraintType);
52126                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52127                         return true;
52128                     }
52129                     // If no inferences can be made to K's constraint, infer from a union of the property types
52130                     // in the source to the template type X.
52131                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52132                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52133                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52134                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52135                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52136                     return true;
52137                 }
52138                 return false;
52139             }
52140             function inferFromObjectTypes(source, target) {
52141                 // If we are already processing another target type with the same associated symbol (such as
52142                 // an instantiation of the same generic type), we do not explore this target as it would yield
52143                 // no further inferences. We exclude the static side of classes from this check since it shares
52144                 // its symbol with the instance side which would lead to false positives.
52145                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52146                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52147                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52148                 if (symbolOrType) {
52149                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52150                         inferencePriority = -1 /* Circularity */;
52151                         return;
52152                     }
52153                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52154                     inferFromObjectTypesWorker(source, target);
52155                     symbolOrTypeStack.pop();
52156                 }
52157                 else {
52158                     inferFromObjectTypesWorker(source, target);
52159                 }
52160             }
52161             function inferFromObjectTypesWorker(source, target) {
52162                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52163                     // If source and target are references to the same generic type, infer from type arguments
52164                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52165                     return;
52166                 }
52167                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52168                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52169                     // from S to T and from X to Y.
52170                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52171                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52172                 }
52173                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52174                     var constraintType = getConstraintTypeFromMappedType(target);
52175                     if (inferToMappedType(source, target, constraintType)) {
52176                         return;
52177                     }
52178                 }
52179                 // Infer from the members of source and target only if the two types are possibly related
52180                 if (!typesDefinitelyUnrelated(source, target)) {
52181                     if (isArrayType(source) || isTupleType(source)) {
52182                         if (isTupleType(target)) {
52183                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52184                             var targetLength = getLengthOfTupleType(target);
52185                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52186                             var targetRestType = getRestTypeOfTupleType(target);
52187                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52188                             for (var i = 0; i < fixedLength; i++) {
52189                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52190                             }
52191                             if (targetRestType) {
52192                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52193                                 if (sourceRestType) {
52194                                     types.push(sourceRestType);
52195                                 }
52196                                 if (types.length) {
52197                                     inferFromTypes(getUnionType(types), targetRestType);
52198                                 }
52199                             }
52200                             return;
52201                         }
52202                         if (isArrayType(target)) {
52203                             inferFromIndexTypes(source, target);
52204                             return;
52205                         }
52206                     }
52207                     inferFromProperties(source, target);
52208                     inferFromSignatures(source, target, 0 /* Call */);
52209                     inferFromSignatures(source, target, 1 /* Construct */);
52210                     inferFromIndexTypes(source, target);
52211                 }
52212             }
52213             function inferFromProperties(source, target) {
52214                 var properties = getPropertiesOfObjectType(target);
52215                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52216                     var targetProp = properties_3[_i];
52217                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52218                     if (sourceProp) {
52219                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52220                     }
52221                 }
52222             }
52223             function inferFromSignatures(source, target, kind) {
52224                 var sourceSignatures = getSignaturesOfType(source, kind);
52225                 var targetSignatures = getSignaturesOfType(target, kind);
52226                 var sourceLen = sourceSignatures.length;
52227                 var targetLen = targetSignatures.length;
52228                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52229                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52230                 for (var i = 0; i < len; i++) {
52231                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52232                 }
52233             }
52234             function inferFromSignature(source, target, skipParameters) {
52235                 if (!skipParameters) {
52236                     var saveBivariant = bivariant;
52237                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52238                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52239                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52240                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52241                     bivariant = saveBivariant;
52242                 }
52243                 applyToReturnTypes(source, target, inferFromTypes);
52244             }
52245             function inferFromIndexTypes(source, target) {
52246                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52247                 if (targetStringIndexType) {
52248                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52249                         getImplicitIndexTypeOfType(source, 0 /* String */);
52250                     if (sourceIndexType) {
52251                         inferFromTypes(sourceIndexType, targetStringIndexType);
52252                     }
52253                 }
52254                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52255                 if (targetNumberIndexType) {
52256                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52257                         getIndexTypeOfType(source, 0 /* String */) ||
52258                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52259                     if (sourceIndexType) {
52260                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52261                     }
52262                 }
52263             }
52264         }
52265         function isTypeOrBaseIdenticalTo(s, t) {
52266             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52267         }
52268         function isTypeCloselyMatchedBy(s, t) {
52269             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52270                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52271         }
52272         function hasPrimitiveConstraint(type) {
52273             var constraint = getConstraintOfTypeParameter(type);
52274             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52275         }
52276         function isObjectLiteralType(type) {
52277             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52278         }
52279         function isObjectOrArrayLiteralType(type) {
52280             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52281         }
52282         function unionObjectAndArrayLiteralCandidates(candidates) {
52283             if (candidates.length > 1) {
52284                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52285                 if (objectLiterals.length) {
52286                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52287                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52288                 }
52289             }
52290             return candidates;
52291         }
52292         function getContravariantInference(inference) {
52293             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52294         }
52295         function getCovariantInference(inference, signature) {
52296             // Extract all object and array literal types and replace them with a single widened and normalized type.
52297             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52298             // We widen inferred literal types if
52299             // all inferences were made to top-level occurrences of the type parameter, and
52300             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52301             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52302             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52303             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52304                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52305             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52306                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52307                     candidates;
52308             // If all inferences were made from a position that implies a combined result, infer a union type.
52309             // Otherwise, infer a common supertype.
52310             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52311                 getUnionType(baseCandidates, 2 /* Subtype */) :
52312                 getCommonSupertype(baseCandidates);
52313             return getWidenedType(unwidenedType);
52314         }
52315         function getInferredType(context, index) {
52316             var inference = context.inferences[index];
52317             if (!inference.inferredType) {
52318                 var inferredType = void 0;
52319                 var signature = context.signature;
52320                 if (signature) {
52321                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52322                     if (inference.contraCandidates) {
52323                         var inferredContravariantType = getContravariantInference(inference);
52324                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52325                         // unless the co-variant inference is a subtype and not 'never'.
52326                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52327                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52328                             inferredCovariantType : inferredContravariantType;
52329                     }
52330                     else if (inferredCovariantType) {
52331                         inferredType = inferredCovariantType;
52332                     }
52333                     else if (context.flags & 1 /* NoDefault */) {
52334                         // We use silentNeverType as the wildcard that signals no inferences.
52335                         inferredType = silentNeverType;
52336                     }
52337                     else {
52338                         // Infer either the default or the empty object type when no inferences were
52339                         // made. It is important to remember that in this case, inference still
52340                         // succeeds, meaning there is no error for not having inference candidates. An
52341                         // inference error only occurs when there are *conflicting* candidates, i.e.
52342                         // candidates with no common supertype.
52343                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52344                         if (defaultType) {
52345                             // Instantiate the default type. Any forward reference to a type
52346                             // parameter should be instantiated to the empty object type.
52347                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52348                         }
52349                     }
52350                 }
52351                 else {
52352                     inferredType = getTypeFromInference(inference);
52353                 }
52354                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52355                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52356                 if (constraint) {
52357                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52358                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52359                         inference.inferredType = inferredType = instantiatedConstraint;
52360                     }
52361                 }
52362             }
52363             return inference.inferredType;
52364         }
52365         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52366             return isInJavaScriptFile ? anyType : unknownType;
52367         }
52368         function getInferredTypes(context) {
52369             var result = [];
52370             for (var i = 0; i < context.inferences.length; i++) {
52371                 result.push(getInferredType(context, i));
52372             }
52373             return result;
52374         }
52375         // EXPRESSION TYPE CHECKING
52376         function getCannotFindNameDiagnosticForName(node) {
52377             switch (node.escapedText) {
52378                 case "document":
52379                 case "console":
52380                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52381                 case "$":
52382                     return compilerOptions.types
52383                         ? 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
52384                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52385                 case "describe":
52386                 case "suite":
52387                 case "it":
52388                 case "test":
52389                     return compilerOptions.types
52390                         ? 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
52391                         : 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;
52392                 case "process":
52393                 case "require":
52394                 case "Buffer":
52395                 case "module":
52396                     return compilerOptions.types
52397                         ? 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
52398                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52399                 case "Map":
52400                 case "Set":
52401                 case "Promise":
52402                 case "Symbol":
52403                 case "WeakMap":
52404                 case "WeakSet":
52405                 case "Iterator":
52406                 case "AsyncIterator":
52407                     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;
52408                 default:
52409                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52410                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52411                     }
52412                     else {
52413                         return ts.Diagnostics.Cannot_find_name_0;
52414                     }
52415             }
52416         }
52417         function getResolvedSymbol(node) {
52418             var links = getNodeLinks(node);
52419             if (!links.resolvedSymbol) {
52420                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52421                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52422                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52423             }
52424             return links.resolvedSymbol;
52425         }
52426         function isInTypeQuery(node) {
52427             // TypeScript 1.0 spec (April 2014): 3.6.3
52428             // A type query consists of the keyword typeof followed by an expression.
52429             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52430             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52431         }
52432         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52433         // separated by dots). The key consists of the id of the symbol referenced by the
52434         // leftmost identifier followed by zero or more property names separated by dots.
52435         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52436         // occurring in an apparent type position with '@' because the control flow type
52437         // of such nodes may be based on the apparent type instead of the declared type.
52438         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52439             switch (node.kind) {
52440                 case 75 /* Identifier */:
52441                     var symbol = getResolvedSymbol(node);
52442                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52443                 case 104 /* ThisKeyword */:
52444                     return "0";
52445                 case 218 /* NonNullExpression */:
52446                 case 200 /* ParenthesizedExpression */:
52447                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52448                 case 194 /* PropertyAccessExpression */:
52449                 case 195 /* ElementAccessExpression */:
52450                     var propName = getAccessedPropertyName(node);
52451                     if (propName !== undefined) {
52452                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52453                         return key && key + "." + propName;
52454                     }
52455             }
52456             return undefined;
52457         }
52458         function isMatchingReference(source, target) {
52459             switch (target.kind) {
52460                 case 200 /* ParenthesizedExpression */:
52461                 case 218 /* NonNullExpression */:
52462                     return isMatchingReference(source, target.expression);
52463             }
52464             switch (source.kind) {
52465                 case 75 /* Identifier */:
52466                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52467                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52468                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52469                 case 104 /* ThisKeyword */:
52470                     return target.kind === 104 /* ThisKeyword */;
52471                 case 102 /* SuperKeyword */:
52472                     return target.kind === 102 /* SuperKeyword */;
52473                 case 218 /* NonNullExpression */:
52474                 case 200 /* ParenthesizedExpression */:
52475                     return isMatchingReference(source.expression, target);
52476                 case 194 /* PropertyAccessExpression */:
52477                 case 195 /* ElementAccessExpression */:
52478                     return ts.isAccessExpression(target) &&
52479                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52480                         isMatchingReference(source.expression, target.expression);
52481             }
52482             return false;
52483         }
52484         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52485         function containsTruthyCheck(source, target) {
52486             return isMatchingReference(source, target) ||
52487                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52488                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52489         }
52490         function getAccessedPropertyName(access) {
52491             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52492                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52493                     undefined;
52494         }
52495         function containsMatchingReference(source, target) {
52496             while (ts.isAccessExpression(source)) {
52497                 source = source.expression;
52498                 if (isMatchingReference(source, target)) {
52499                     return true;
52500                 }
52501             }
52502             return false;
52503         }
52504         function optionalChainContainsReference(source, target) {
52505             while (ts.isOptionalChain(source)) {
52506                 source = source.expression;
52507                 if (isMatchingReference(source, target)) {
52508                     return true;
52509                 }
52510             }
52511             return false;
52512         }
52513         function isDiscriminantProperty(type, name) {
52514             if (type && type.flags & 1048576 /* Union */) {
52515                 var prop = getUnionOrIntersectionProperty(type, name);
52516                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52517                     if (prop.isDiscriminantProperty === undefined) {
52518                         prop.isDiscriminantProperty =
52519                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52520                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52521                     }
52522                     return !!prop.isDiscriminantProperty;
52523                 }
52524             }
52525             return false;
52526         }
52527         function findDiscriminantProperties(sourceProperties, target) {
52528             var result;
52529             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52530                 var sourceProperty = sourceProperties_2[_i];
52531                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52532                     if (result) {
52533                         result.push(sourceProperty);
52534                         continue;
52535                     }
52536                     result = [sourceProperty];
52537                 }
52538             }
52539             return result;
52540         }
52541         function isOrContainsMatchingReference(source, target) {
52542             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52543         }
52544         function hasMatchingArgument(callExpression, reference) {
52545             if (callExpression.arguments) {
52546                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52547                     var argument = _a[_i];
52548                     if (isOrContainsMatchingReference(reference, argument)) {
52549                         return true;
52550                     }
52551                 }
52552             }
52553             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52554                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52555                 return true;
52556             }
52557             return false;
52558         }
52559         function getFlowNodeId(flow) {
52560             if (!flow.id || flow.id < 0) {
52561                 flow.id = nextFlowId;
52562                 nextFlowId++;
52563             }
52564             return flow.id;
52565         }
52566         function typeMaybeAssignableTo(source, target) {
52567             if (!(source.flags & 1048576 /* Union */)) {
52568                 return isTypeAssignableTo(source, target);
52569             }
52570             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52571                 var t = _a[_i];
52572                 if (isTypeAssignableTo(t, target)) {
52573                     return true;
52574                 }
52575             }
52576             return false;
52577         }
52578         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52579         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52580         // we remove type string.
52581         function getAssignmentReducedType(declaredType, assignedType) {
52582             if (declaredType !== assignedType) {
52583                 if (assignedType.flags & 131072 /* Never */) {
52584                     return assignedType;
52585                 }
52586                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52587                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52588                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52589                 }
52590                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52591                 // For now, when that happens, we give up and don't narrow at all.  (This also
52592                 // means we'll never narrow for erroneous assignments where the assigned type
52593                 // is not assignable to the declared type.)
52594                 if (isTypeAssignableTo(assignedType, reducedType)) {
52595                     return reducedType;
52596                 }
52597             }
52598             return declaredType;
52599         }
52600         function getTypeFactsOfTypes(types) {
52601             var result = 0 /* None */;
52602             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52603                 var t = types_15[_i];
52604                 result |= getTypeFacts(t);
52605             }
52606             return result;
52607         }
52608         function isFunctionObjectType(type) {
52609             // We do a quick check for a "bind" property before performing the more expensive subtype
52610             // check. This gives us a quicker out in the common case where an object type is not a function.
52611             var resolved = resolveStructuredTypeMembers(type);
52612             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52613                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52614         }
52615         function getTypeFacts(type) {
52616             var flags = type.flags;
52617             if (flags & 4 /* String */) {
52618                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52619             }
52620             if (flags & 128 /* StringLiteral */) {
52621                 var isEmpty = type.value === "";
52622                 return strictNullChecks ?
52623                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52624                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52625             }
52626             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52627                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52628             }
52629             if (flags & 256 /* NumberLiteral */) {
52630                 var isZero = type.value === 0;
52631                 return strictNullChecks ?
52632                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52633                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52634             }
52635             if (flags & 64 /* BigInt */) {
52636                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52637             }
52638             if (flags & 2048 /* BigIntLiteral */) {
52639                 var isZero = isZeroBigInt(type);
52640                 return strictNullChecks ?
52641                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52642                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52643             }
52644             if (flags & 16 /* Boolean */) {
52645                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52646             }
52647             if (flags & 528 /* BooleanLike */) {
52648                 return strictNullChecks ?
52649                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52650                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52651             }
52652             if (flags & 524288 /* Object */) {
52653                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52654                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52655                     isFunctionObjectType(type) ?
52656                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52657                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52658             }
52659             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52660                 return 9830144 /* UndefinedFacts */;
52661             }
52662             if (flags & 65536 /* Null */) {
52663                 return 9363232 /* NullFacts */;
52664             }
52665             if (flags & 12288 /* ESSymbolLike */) {
52666                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52667             }
52668             if (flags & 67108864 /* NonPrimitive */) {
52669                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52670             }
52671             if (flags & 131072 /* Never */) {
52672                 return 0 /* None */;
52673             }
52674             if (flags & 63176704 /* Instantiable */) {
52675                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52676             }
52677             if (flags & 3145728 /* UnionOrIntersection */) {
52678                 return getTypeFactsOfTypes(type.types);
52679             }
52680             return 16777215 /* All */;
52681         }
52682         function getTypeWithFacts(type, include) {
52683             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52684         }
52685         function getTypeWithDefault(type, defaultExpression) {
52686             if (defaultExpression) {
52687                 var defaultType = getTypeOfExpression(defaultExpression);
52688                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52689             }
52690             return type;
52691         }
52692         function getTypeOfDestructuredProperty(type, name) {
52693             var nameType = getLiteralTypeFromPropertyName(name);
52694             if (!isTypeUsableAsPropertyName(nameType))
52695                 return errorType;
52696             var text = getPropertyNameFromType(nameType);
52697             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52698                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52699                 getIndexTypeOfType(type, 0 /* String */) ||
52700                 errorType;
52701         }
52702         function getTypeOfDestructuredArrayElement(type, index) {
52703             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52704                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52705                 errorType;
52706         }
52707         function getTypeOfDestructuredSpreadExpression(type) {
52708             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52709         }
52710         function getAssignedTypeOfBinaryExpression(node) {
52711             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52712                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52713             return isDestructuringDefaultAssignment ?
52714                 getTypeWithDefault(getAssignedType(node), node.right) :
52715                 getTypeOfExpression(node.right);
52716         }
52717         function isDestructuringAssignmentTarget(parent) {
52718             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52719                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52720         }
52721         function getAssignedTypeOfArrayLiteralElement(node, element) {
52722             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52723         }
52724         function getAssignedTypeOfSpreadExpression(node) {
52725             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52726         }
52727         function getAssignedTypeOfPropertyAssignment(node) {
52728             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52729         }
52730         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52731             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52732         }
52733         function getAssignedType(node) {
52734             var parent = node.parent;
52735             switch (parent.kind) {
52736                 case 231 /* ForInStatement */:
52737                     return stringType;
52738                 case 232 /* ForOfStatement */:
52739                     return checkRightHandSideOfForOf(parent) || errorType;
52740                 case 209 /* BinaryExpression */:
52741                     return getAssignedTypeOfBinaryExpression(parent);
52742                 case 203 /* DeleteExpression */:
52743                     return undefinedType;
52744                 case 192 /* ArrayLiteralExpression */:
52745                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52746                 case 213 /* SpreadElement */:
52747                     return getAssignedTypeOfSpreadExpression(parent);
52748                 case 281 /* PropertyAssignment */:
52749                     return getAssignedTypeOfPropertyAssignment(parent);
52750                 case 282 /* ShorthandPropertyAssignment */:
52751                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52752             }
52753             return errorType;
52754         }
52755         function getInitialTypeOfBindingElement(node) {
52756             var pattern = node.parent;
52757             var parentType = getInitialType(pattern.parent);
52758             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52759                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52760                 !node.dotDotDotToken ?
52761                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52762                     getTypeOfDestructuredSpreadExpression(parentType);
52763             return getTypeWithDefault(type, node.initializer);
52764         }
52765         function getTypeOfInitializer(node) {
52766             // Return the cached type if one is available. If the type of the variable was inferred
52767             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52768             // without caching such that transient types are reflected.
52769             var links = getNodeLinks(node);
52770             return links.resolvedType || getTypeOfExpression(node);
52771         }
52772         function getInitialTypeOfVariableDeclaration(node) {
52773             if (node.initializer) {
52774                 return getTypeOfInitializer(node.initializer);
52775             }
52776             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52777                 return stringType;
52778             }
52779             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52780                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52781             }
52782             return errorType;
52783         }
52784         function getInitialType(node) {
52785             return node.kind === 242 /* VariableDeclaration */ ?
52786                 getInitialTypeOfVariableDeclaration(node) :
52787                 getInitialTypeOfBindingElement(node);
52788         }
52789         function isEmptyArrayAssignment(node) {
52790             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52791                 isEmptyArrayLiteral(node.initializer) ||
52792                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52793                     isEmptyArrayLiteral(node.parent.right);
52794         }
52795         function getReferenceCandidate(node) {
52796             switch (node.kind) {
52797                 case 200 /* ParenthesizedExpression */:
52798                     return getReferenceCandidate(node.expression);
52799                 case 209 /* BinaryExpression */:
52800                     switch (node.operatorToken.kind) {
52801                         case 62 /* EqualsToken */:
52802                             return getReferenceCandidate(node.left);
52803                         case 27 /* CommaToken */:
52804                             return getReferenceCandidate(node.right);
52805                     }
52806             }
52807             return node;
52808         }
52809         function getReferenceRoot(node) {
52810             var parent = node.parent;
52811             return parent.kind === 200 /* ParenthesizedExpression */ ||
52812                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52813                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52814                 getReferenceRoot(parent) : node;
52815         }
52816         function getTypeOfSwitchClause(clause) {
52817             if (clause.kind === 277 /* CaseClause */) {
52818                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52819             }
52820             return neverType;
52821         }
52822         function getSwitchClauseTypes(switchStatement) {
52823             var links = getNodeLinks(switchStatement);
52824             if (!links.switchTypes) {
52825                 links.switchTypes = [];
52826                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52827                     var clause = _a[_i];
52828                     links.switchTypes.push(getTypeOfSwitchClause(clause));
52829                 }
52830             }
52831             return links.switchTypes;
52832         }
52833         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
52834             var witnesses = [];
52835             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52836                 var clause = _a[_i];
52837                 if (clause.kind === 277 /* CaseClause */) {
52838                     if (ts.isStringLiteralLike(clause.expression)) {
52839                         witnesses.push(clause.expression.text);
52840                         continue;
52841                     }
52842                     return ts.emptyArray;
52843                 }
52844                 if (retainDefault)
52845                     witnesses.push(/*explicitDefaultStatement*/ undefined);
52846             }
52847             return witnesses;
52848         }
52849         function eachTypeContainedIn(source, types) {
52850             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
52851         }
52852         function isTypeSubsetOf(source, target) {
52853             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
52854         }
52855         function isTypeSubsetOfUnion(source, target) {
52856             if (source.flags & 1048576 /* Union */) {
52857                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52858                     var t = _a[_i];
52859                     if (!containsType(target.types, t)) {
52860                         return false;
52861                     }
52862                 }
52863                 return true;
52864             }
52865             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
52866                 return true;
52867             }
52868             return containsType(target.types, source);
52869         }
52870         function forEachType(type, f) {
52871             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
52872         }
52873         function everyType(type, f) {
52874             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
52875         }
52876         function filterType(type, f) {
52877             if (type.flags & 1048576 /* Union */) {
52878                 var types = type.types;
52879                 var filtered = ts.filter(types, f);
52880                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
52881             }
52882             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
52883         }
52884         function countTypes(type) {
52885             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
52886         }
52887         function mapType(type, mapper, noReductions) {
52888             if (type.flags & 131072 /* Never */) {
52889                 return type;
52890             }
52891             if (!(type.flags & 1048576 /* Union */)) {
52892                 return mapper(type);
52893             }
52894             var mappedTypes;
52895             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52896                 var t = _a[_i];
52897                 var mapped = mapper(t);
52898                 if (mapped) {
52899                     if (!mappedTypes) {
52900                         mappedTypes = [mapped];
52901                     }
52902                     else {
52903                         mappedTypes.push(mapped);
52904                     }
52905                 }
52906             }
52907             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
52908         }
52909         function extractTypesOfKind(type, kind) {
52910             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
52911         }
52912         // Return a new type in which occurrences of the string and number primitive types in
52913         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
52914         // literals in typeWithLiterals, respectively.
52915         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
52916             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
52917                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
52918                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
52919                 return mapType(typeWithPrimitives, function (t) {
52920                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
52921                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
52922                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
52923                 });
52924             }
52925             return typeWithPrimitives;
52926         }
52927         function isIncomplete(flowType) {
52928             return flowType.flags === 0;
52929         }
52930         function getTypeFromFlowType(flowType) {
52931             return flowType.flags === 0 ? flowType.type : flowType;
52932         }
52933         function createFlowType(type, incomplete) {
52934             return incomplete ? { flags: 0, type: type } : type;
52935         }
52936         // An evolving array type tracks the element types that have so far been seen in an
52937         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
52938         // array types are ultimately converted into manifest array types (using getFinalArrayType)
52939         // and never escape the getFlowTypeOfReference function.
52940         function createEvolvingArrayType(elementType) {
52941             var result = createObjectType(256 /* EvolvingArray */);
52942             result.elementType = elementType;
52943             return result;
52944         }
52945         function getEvolvingArrayType(elementType) {
52946             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
52947         }
52948         // When adding evolving array element types we do not perform subtype reduction. Instead,
52949         // we defer subtype reduction until the evolving array type is finalized into a manifest
52950         // array type.
52951         function addEvolvingArrayElementType(evolvingArrayType, node) {
52952             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
52953             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
52954         }
52955         function createFinalArrayType(elementType) {
52956             return elementType.flags & 131072 /* Never */ ?
52957                 autoArrayType :
52958                 createArrayType(elementType.flags & 1048576 /* Union */ ?
52959                     getUnionType(elementType.types, 2 /* Subtype */) :
52960                     elementType);
52961         }
52962         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
52963         function getFinalArrayType(evolvingArrayType) {
52964             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
52965         }
52966         function finalizeEvolvingArrayType(type) {
52967             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
52968         }
52969         function getElementTypeOfEvolvingArrayType(type) {
52970             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
52971         }
52972         function isEvolvingArrayTypeList(types) {
52973             var hasEvolvingArrayType = false;
52974             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
52975                 var t = types_16[_i];
52976                 if (!(t.flags & 131072 /* Never */)) {
52977                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
52978                         return false;
52979                     }
52980                     hasEvolvingArrayType = true;
52981                 }
52982             }
52983             return hasEvolvingArrayType;
52984         }
52985         // At flow control branch or loop junctions, if the type along every antecedent code path
52986         // is an evolving array type, we construct a combined evolving array type. Otherwise we
52987         // finalize all evolving array types.
52988         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
52989             return isEvolvingArrayTypeList(types) ?
52990                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
52991                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
52992         }
52993         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
52994         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
52995         function isEvolvingArrayOperationTarget(node) {
52996             var root = getReferenceRoot(node);
52997             var parent = root.parent;
52998             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
52999                 parent.parent.kind === 196 /* CallExpression */
53000                     && ts.isIdentifier(parent.name)
53001                     && ts.isPushOrUnshiftIdentifier(parent.name));
53002             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53003                 parent.expression === root &&
53004                 parent.parent.kind === 209 /* BinaryExpression */ &&
53005                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53006                 parent.parent.left === parent &&
53007                 !ts.isAssignmentTarget(parent.parent) &&
53008                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53009             return isLengthPushOrUnshift || isElementAssignment;
53010         }
53011         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53012             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53013                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53014                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53015         }
53016         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53017             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53018                 return getTypeOfSymbol(symbol);
53019             }
53020             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53021                 var declaration = symbol.valueDeclaration;
53022                 if (declaration) {
53023                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53024                         return getTypeOfSymbol(symbol);
53025                     }
53026                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53027                         var statement = declaration.parent.parent;
53028                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53029                         if (expressionType) {
53030                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53031                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53032                         }
53033                     }
53034                     if (diagnostic) {
53035                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53036                     }
53037                 }
53038             }
53039         }
53040         // We require the dotted function name in an assertion expression to be comprised of identifiers
53041         // that reference function, method, class or value module symbols; or variable, property or
53042         // parameter symbols with declarations that have explicit type annotations. Such references are
53043         // resolvable with no possibility of triggering circularities in control flow analysis.
53044         function getTypeOfDottedName(node, diagnostic) {
53045             if (!(node.flags & 16777216 /* InWithStatement */)) {
53046                 switch (node.kind) {
53047                     case 75 /* Identifier */:
53048                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53049                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53050                     case 104 /* ThisKeyword */:
53051                         return getExplicitThisType(node);
53052                     case 102 /* SuperKeyword */:
53053                         return checkSuperExpression(node);
53054                     case 194 /* PropertyAccessExpression */:
53055                         var type = getTypeOfDottedName(node.expression, diagnostic);
53056                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53057                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53058                     case 200 /* ParenthesizedExpression */:
53059                         return getTypeOfDottedName(node.expression, diagnostic);
53060                 }
53061             }
53062         }
53063         function getEffectsSignature(node) {
53064             var links = getNodeLinks(node);
53065             var signature = links.effectsSignature;
53066             if (signature === undefined) {
53067                 // A call expression parented by an expression statement is a potential assertion. Other call
53068                 // expressions are potential type predicate function calls. In order to avoid triggering
53069                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53070                 // target expression of an assertion.
53071                 var funcType = void 0;
53072                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53073                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53074                 }
53075                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53076                     if (ts.isOptionalChain(node)) {
53077                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53078                     }
53079                     else {
53080                         funcType = checkNonNullExpression(node.expression);
53081                     }
53082                 }
53083                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53084                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53085                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53086                         undefined;
53087                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53088             }
53089             return signature === unknownSignature ? undefined : signature;
53090         }
53091         function hasTypePredicateOrNeverReturnType(signature) {
53092             return !!(getTypePredicateOfSignature(signature) ||
53093                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53094         }
53095         function getTypePredicateArgument(predicate, callExpression) {
53096             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53097                 return callExpression.arguments[predicate.parameterIndex];
53098             }
53099             var invokedExpression = ts.skipParentheses(callExpression.expression);
53100             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53101         }
53102         function reportFlowControlError(node) {
53103             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53104             var sourceFile = ts.getSourceFileOfNode(node);
53105             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53106             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53107         }
53108         function isReachableFlowNode(flow) {
53109             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53110             lastFlowNode = flow;
53111             lastFlowNodeReachable = result;
53112             return result;
53113         }
53114         function isFalseExpression(expr) {
53115             var node = ts.skipParentheses(expr);
53116             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53117                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53118         }
53119         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53120             while (true) {
53121                 if (flow === lastFlowNode) {
53122                     return lastFlowNodeReachable;
53123                 }
53124                 var flags = flow.flags;
53125                 if (flags & 4096 /* Shared */) {
53126                     if (!noCacheCheck) {
53127                         var id = getFlowNodeId(flow);
53128                         var reachable = flowNodeReachable[id];
53129                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53130                     }
53131                     noCacheCheck = false;
53132                 }
53133                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53134                     flow = flow.antecedent;
53135                 }
53136                 else if (flags & 512 /* Call */) {
53137                     var signature = getEffectsSignature(flow.node);
53138                     if (signature) {
53139                         var predicate = getTypePredicateOfSignature(signature);
53140                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53141                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53142                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53143                                 return false;
53144                             }
53145                         }
53146                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53147                             return false;
53148                         }
53149                     }
53150                     flow = flow.antecedent;
53151                 }
53152                 else if (flags & 4 /* BranchLabel */) {
53153                     // A branching point is reachable if any branch is reachable.
53154                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53155                 }
53156                 else if (flags & 8 /* LoopLabel */) {
53157                     // A loop is reachable if the control flow path that leads to the top is reachable.
53158                     flow = flow.antecedents[0];
53159                 }
53160                 else if (flags & 128 /* SwitchClause */) {
53161                     // The control flow path representing an unmatched value in a switch statement with
53162                     // no default clause is unreachable if the switch statement is exhaustive.
53163                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53164                         return false;
53165                     }
53166                     flow = flow.antecedent;
53167                 }
53168                 else if (flags & 1024 /* ReduceLabel */) {
53169                     // Cache is unreliable once we start adjusting labels
53170                     lastFlowNode = undefined;
53171                     var target = flow.target;
53172                     var saveAntecedents = target.antecedents;
53173                     target.antecedents = flow.antecedents;
53174                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53175                     target.antecedents = saveAntecedents;
53176                     return result;
53177                 }
53178                 else {
53179                     return !(flags & 1 /* Unreachable */);
53180                 }
53181             }
53182         }
53183         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53184             if (initialType === void 0) { initialType = declaredType; }
53185             var key;
53186             var keySet = false;
53187             var flowDepth = 0;
53188             if (flowAnalysisDisabled) {
53189                 return errorType;
53190             }
53191             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53192                 return declaredType;
53193             }
53194             flowInvocationCount++;
53195             var sharedFlowStart = sharedFlowCount;
53196             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53197             sharedFlowCount = sharedFlowStart;
53198             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53199             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53200             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53201             // type mismatch errors.
53202             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53203             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53204                 return declaredType;
53205             }
53206             return resultType;
53207             function getOrSetCacheKey() {
53208                 if (keySet) {
53209                     return key;
53210                 }
53211                 keySet = true;
53212                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53213             }
53214             function getTypeAtFlowNode(flow) {
53215                 if (flowDepth === 2000) {
53216                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53217                     // and disable further control flow analysis in the containing function or module body.
53218                     flowAnalysisDisabled = true;
53219                     reportFlowControlError(reference);
53220                     return errorType;
53221                 }
53222                 flowDepth++;
53223                 while (true) {
53224                     var flags = flow.flags;
53225                     if (flags & 4096 /* Shared */) {
53226                         // We cache results of flow type resolution for shared nodes that were previously visited in
53227                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53228                         // antecedent of more than one node.
53229                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53230                             if (sharedFlowNodes[i] === flow) {
53231                                 flowDepth--;
53232                                 return sharedFlowTypes[i];
53233                             }
53234                         }
53235                     }
53236                     var type = void 0;
53237                     if (flags & 16 /* Assignment */) {
53238                         type = getTypeAtFlowAssignment(flow);
53239                         if (!type) {
53240                             flow = flow.antecedent;
53241                             continue;
53242                         }
53243                     }
53244                     else if (flags & 512 /* Call */) {
53245                         type = getTypeAtFlowCall(flow);
53246                         if (!type) {
53247                             flow = flow.antecedent;
53248                             continue;
53249                         }
53250                     }
53251                     else if (flags & 96 /* Condition */) {
53252                         type = getTypeAtFlowCondition(flow);
53253                     }
53254                     else if (flags & 128 /* SwitchClause */) {
53255                         type = getTypeAtSwitchClause(flow);
53256                     }
53257                     else if (flags & 12 /* Label */) {
53258                         if (flow.antecedents.length === 1) {
53259                             flow = flow.antecedents[0];
53260                             continue;
53261                         }
53262                         type = flags & 4 /* BranchLabel */ ?
53263                             getTypeAtFlowBranchLabel(flow) :
53264                             getTypeAtFlowLoopLabel(flow);
53265                     }
53266                     else if (flags & 256 /* ArrayMutation */) {
53267                         type = getTypeAtFlowArrayMutation(flow);
53268                         if (!type) {
53269                             flow = flow.antecedent;
53270                             continue;
53271                         }
53272                     }
53273                     else if (flags & 1024 /* ReduceLabel */) {
53274                         var target = flow.target;
53275                         var saveAntecedents = target.antecedents;
53276                         target.antecedents = flow.antecedents;
53277                         type = getTypeAtFlowNode(flow.antecedent);
53278                         target.antecedents = saveAntecedents;
53279                     }
53280                     else if (flags & 2 /* Start */) {
53281                         // Check if we should continue with the control flow of the containing function.
53282                         var container = flow.node;
53283                         if (container && container !== flowContainer &&
53284                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53285                             reference.kind !== 195 /* ElementAccessExpression */ &&
53286                             reference.kind !== 104 /* ThisKeyword */) {
53287                             flow = container.flowNode;
53288                             continue;
53289                         }
53290                         // At the top of the flow we have the initial type.
53291                         type = initialType;
53292                     }
53293                     else {
53294                         // Unreachable code errors are reported in the binding phase. Here we
53295                         // simply return the non-auto declared type to reduce follow-on errors.
53296                         type = convertAutoToAny(declaredType);
53297                     }
53298                     if (flags & 4096 /* Shared */) {
53299                         // Record visited node and the associated type in the cache.
53300                         sharedFlowNodes[sharedFlowCount] = flow;
53301                         sharedFlowTypes[sharedFlowCount] = type;
53302                         sharedFlowCount++;
53303                     }
53304                     flowDepth--;
53305                     return type;
53306                 }
53307             }
53308             function getInitialOrAssignedType(flow) {
53309                 var node = flow.node;
53310                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53311                     getInitialType(node) :
53312                     getAssignedType(node), reference);
53313             }
53314             function getTypeAtFlowAssignment(flow) {
53315                 var node = flow.node;
53316                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53317                 // only need to evaluate the assigned type if the declared type is a union type.
53318                 if (isMatchingReference(reference, node)) {
53319                     if (!isReachableFlowNode(flow)) {
53320                         return unreachableNeverType;
53321                     }
53322                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53323                         var flowType = getTypeAtFlowNode(flow.antecedent);
53324                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53325                     }
53326                     if (declaredType === autoType || declaredType === autoArrayType) {
53327                         if (isEmptyArrayAssignment(node)) {
53328                             return getEvolvingArrayType(neverType);
53329                         }
53330                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53331                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53332                     }
53333                     if (declaredType.flags & 1048576 /* Union */) {
53334                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53335                     }
53336                     return declaredType;
53337                 }
53338                 // We didn't have a direct match. However, if the reference is a dotted name, this
53339                 // may be an assignment to a left hand part of the reference. For example, for a
53340                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53341                 // return the declared type.
53342                 if (containsMatchingReference(reference, node)) {
53343                     if (!isReachableFlowNode(flow)) {
53344                         return unreachableNeverType;
53345                     }
53346                     // A matching dotted name might also be an expando property on a function *expression*,
53347                     // in which case we continue control flow analysis back to the function's declaration
53348                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53349                         var init = ts.getDeclaredExpandoInitializer(node);
53350                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53351                             return getTypeAtFlowNode(flow.antecedent);
53352                         }
53353                     }
53354                     return declaredType;
53355                 }
53356                 // for (const _ in ref) acts as a nonnull on ref
53357                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53358                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53359                 }
53360                 // Assignment doesn't affect reference
53361                 return undefined;
53362             }
53363             function narrowTypeByAssertion(type, expr) {
53364                 var node = ts.skipParentheses(expr);
53365                 if (node.kind === 91 /* FalseKeyword */) {
53366                     return unreachableNeverType;
53367                 }
53368                 if (node.kind === 209 /* BinaryExpression */) {
53369                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53370                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53371                     }
53372                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53373                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53374                     }
53375                 }
53376                 return narrowType(type, node, /*assumeTrue*/ true);
53377             }
53378             function getTypeAtFlowCall(flow) {
53379                 var signature = getEffectsSignature(flow.node);
53380                 if (signature) {
53381                     var predicate = getTypePredicateOfSignature(signature);
53382                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53383                         var flowType = getTypeAtFlowNode(flow.antecedent);
53384                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53385                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53386                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53387                                 type;
53388                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53389                     }
53390                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53391                         return unreachableNeverType;
53392                     }
53393                 }
53394                 return undefined;
53395             }
53396             function getTypeAtFlowArrayMutation(flow) {
53397                 if (declaredType === autoType || declaredType === autoArrayType) {
53398                     var node = flow.node;
53399                     var expr = node.kind === 196 /* CallExpression */ ?
53400                         node.expression.expression :
53401                         node.left.expression;
53402                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53403                         var flowType = getTypeAtFlowNode(flow.antecedent);
53404                         var type = getTypeFromFlowType(flowType);
53405                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53406                             var evolvedType_1 = type;
53407                             if (node.kind === 196 /* CallExpression */) {
53408                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53409                                     var arg = _a[_i];
53410                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53411                                 }
53412                             }
53413                             else {
53414                                 // 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)
53415                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53416                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53417                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53418                                 }
53419                             }
53420                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53421                         }
53422                         return flowType;
53423                     }
53424                 }
53425                 return undefined;
53426             }
53427             function getTypeAtFlowCondition(flow) {
53428                 var flowType = getTypeAtFlowNode(flow.antecedent);
53429                 var type = getTypeFromFlowType(flowType);
53430                 if (type.flags & 131072 /* Never */) {
53431                     return flowType;
53432                 }
53433                 // If we have an antecedent type (meaning we're reachable in some way), we first
53434                 // attempt to narrow the antecedent type. If that produces the never type, and if
53435                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53436                 // take the type guard as an indication that control *could* reach here once we
53437                 // have the complete type. We proceed by switching to the silent never type which
53438                 // doesn't report errors when operators are applied to it. Note that this is the
53439                 // *only* place a silent never type is ever generated.
53440                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53441                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53442                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53443                 if (narrowedType === nonEvolvingType) {
53444                     return flowType;
53445                 }
53446                 var incomplete = isIncomplete(flowType);
53447                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53448                 return createFlowType(resultType, incomplete);
53449             }
53450             function getTypeAtSwitchClause(flow) {
53451                 var expr = flow.switchStatement.expression;
53452                 var flowType = getTypeAtFlowNode(flow.antecedent);
53453                 var type = getTypeFromFlowType(flowType);
53454                 if (isMatchingReference(reference, expr)) {
53455                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53456                 }
53457                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53458                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53459                 }
53460                 else {
53461                     if (strictNullChecks) {
53462                         if (optionalChainContainsReference(expr, reference)) {
53463                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53464                         }
53465                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53466                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53467                         }
53468                     }
53469                     if (isMatchingReferenceDiscriminant(expr, type)) {
53470                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53471                     }
53472                 }
53473                 return createFlowType(type, isIncomplete(flowType));
53474             }
53475             function getTypeAtFlowBranchLabel(flow) {
53476                 var antecedentTypes = [];
53477                 var subtypeReduction = false;
53478                 var seenIncomplete = false;
53479                 var bypassFlow;
53480                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53481                     var antecedent = _a[_i];
53482                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53483                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53484                         bypassFlow = antecedent;
53485                         continue;
53486                     }
53487                     var flowType = getTypeAtFlowNode(antecedent);
53488                     var type = getTypeFromFlowType(flowType);
53489                     // If the type at a particular antecedent path is the declared type and the
53490                     // reference is known to always be assigned (i.e. when declared and initial types
53491                     // are the same), there is no reason to process more antecedents since the only
53492                     // possible outcome is subtypes that will be removed in the final union type anyway.
53493                     if (type === declaredType && declaredType === initialType) {
53494                         return type;
53495                     }
53496                     ts.pushIfUnique(antecedentTypes, type);
53497                     // If an antecedent type is not a subset of the declared type, we need to perform
53498                     // subtype reduction. This happens when a "foreign" type is injected into the control
53499                     // flow using the instanceof operator or a user defined type predicate.
53500                     if (!isTypeSubsetOf(type, declaredType)) {
53501                         subtypeReduction = true;
53502                     }
53503                     if (isIncomplete(flowType)) {
53504                         seenIncomplete = true;
53505                     }
53506                 }
53507                 if (bypassFlow) {
53508                     var flowType = getTypeAtFlowNode(bypassFlow);
53509                     var type = getTypeFromFlowType(flowType);
53510                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53511                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53512                     // the risk of circularities, we only want to perform them when they make a difference.
53513                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53514                         if (type === declaredType && declaredType === initialType) {
53515                             return type;
53516                         }
53517                         antecedentTypes.push(type);
53518                         if (!isTypeSubsetOf(type, declaredType)) {
53519                             subtypeReduction = true;
53520                         }
53521                         if (isIncomplete(flowType)) {
53522                             seenIncomplete = true;
53523                         }
53524                     }
53525                 }
53526                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53527             }
53528             function getTypeAtFlowLoopLabel(flow) {
53529                 // If we have previously computed the control flow type for the reference at
53530                 // this flow loop junction, return the cached type.
53531                 var id = getFlowNodeId(flow);
53532                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53533                 var key = getOrSetCacheKey();
53534                 if (!key) {
53535                     // No cache key is generated when binding patterns are in unnarrowable situations
53536                     return declaredType;
53537                 }
53538                 var cached = cache.get(key);
53539                 if (cached) {
53540                     return cached;
53541                 }
53542                 // If this flow loop junction and reference are already being processed, return
53543                 // the union of the types computed for each branch so far, marked as incomplete.
53544                 // It is possible to see an empty array in cases where loops are nested and the
53545                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53546                 // In such cases we restart the analysis of the inner loop, which will then see
53547                 // a non-empty in-process array for the outer loop and eventually terminate because
53548                 // the first antecedent of a loop junction is always the non-looping control flow
53549                 // path that leads to the top.
53550                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53551                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53552                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53553                     }
53554                 }
53555                 // Add the flow loop junction and reference to the in-process stack and analyze
53556                 // each antecedent code path.
53557                 var antecedentTypes = [];
53558                 var subtypeReduction = false;
53559                 var firstAntecedentType;
53560                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53561                     var antecedent = _a[_i];
53562                     var flowType = void 0;
53563                     if (!firstAntecedentType) {
53564                         // The first antecedent of a loop junction is always the non-looping control
53565                         // flow path that leads to the top.
53566                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53567                     }
53568                     else {
53569                         // All but the first antecedent are the looping control flow paths that lead
53570                         // back to the loop junction. We track these on the flow loop stack.
53571                         flowLoopNodes[flowLoopCount] = flow;
53572                         flowLoopKeys[flowLoopCount] = key;
53573                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53574                         flowLoopCount++;
53575                         var saveFlowTypeCache = flowTypeCache;
53576                         flowTypeCache = undefined;
53577                         flowType = getTypeAtFlowNode(antecedent);
53578                         flowTypeCache = saveFlowTypeCache;
53579                         flowLoopCount--;
53580                         // If we see a value appear in the cache it is a sign that control flow analysis
53581                         // was restarted and completed by checkExpressionCached. We can simply pick up
53582                         // the resulting type and bail out.
53583                         var cached_1 = cache.get(key);
53584                         if (cached_1) {
53585                             return cached_1;
53586                         }
53587                     }
53588                     var type = getTypeFromFlowType(flowType);
53589                     ts.pushIfUnique(antecedentTypes, type);
53590                     // If an antecedent type is not a subset of the declared type, we need to perform
53591                     // subtype reduction. This happens when a "foreign" type is injected into the control
53592                     // flow using the instanceof operator or a user defined type predicate.
53593                     if (!isTypeSubsetOf(type, declaredType)) {
53594                         subtypeReduction = true;
53595                     }
53596                     // If the type at a particular antecedent path is the declared type there is no
53597                     // reason to process more antecedents since the only possible outcome is subtypes
53598                     // that will be removed in the final union type anyway.
53599                     if (type === declaredType) {
53600                         break;
53601                     }
53602                 }
53603                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53604                 // is incomplete.
53605                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53606                 if (isIncomplete(firstAntecedentType)) {
53607                     return createFlowType(result, /*incomplete*/ true);
53608                 }
53609                 cache.set(key, result);
53610                 return result;
53611             }
53612             function isMatchingReferenceDiscriminant(expr, computedType) {
53613                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53614                     return false;
53615                 }
53616                 var name = getAccessedPropertyName(expr);
53617                 if (name === undefined) {
53618                     return false;
53619                 }
53620                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53621             }
53622             function narrowTypeByDiscriminant(type, access, narrowType) {
53623                 var propName = getAccessedPropertyName(access);
53624                 if (propName === undefined) {
53625                     return type;
53626                 }
53627                 var propType = getTypeOfPropertyOfType(type, propName);
53628                 if (!propType) {
53629                     return type;
53630                 }
53631                 var narrowedPropType = narrowType(propType);
53632                 return filterType(type, function (t) {
53633                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53634                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53635                 });
53636             }
53637             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53638                 if (isMatchingReference(reference, expr)) {
53639                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53640                 }
53641                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53642                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53643                 }
53644                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53645                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53646                 }
53647                 return type;
53648             }
53649             function isTypePresencePossible(type, propName, assumeTrue) {
53650                 if (getIndexInfoOfType(type, 0 /* String */)) {
53651                     return true;
53652                 }
53653                 var prop = getPropertyOfType(type, propName);
53654                 if (prop) {
53655                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53656                 }
53657                 return !assumeTrue;
53658             }
53659             function narrowByInKeyword(type, literal, assumeTrue) {
53660                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53661                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53662                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53663                 }
53664                 return type;
53665             }
53666             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53667                 switch (expr.operatorToken.kind) {
53668                     case 62 /* EqualsToken */:
53669                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53670                     case 34 /* EqualsEqualsToken */:
53671                     case 35 /* ExclamationEqualsToken */:
53672                     case 36 /* EqualsEqualsEqualsToken */:
53673                     case 37 /* ExclamationEqualsEqualsToken */:
53674                         var operator_1 = expr.operatorToken.kind;
53675                         var left_1 = getReferenceCandidate(expr.left);
53676                         var right_1 = getReferenceCandidate(expr.right);
53677                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53678                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53679                         }
53680                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53681                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53682                         }
53683                         if (isMatchingReference(reference, left_1)) {
53684                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53685                         }
53686                         if (isMatchingReference(reference, right_1)) {
53687                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53688                         }
53689                         if (strictNullChecks) {
53690                             if (optionalChainContainsReference(left_1, reference)) {
53691                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53692                             }
53693                             else if (optionalChainContainsReference(right_1, reference)) {
53694                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53695                             }
53696                         }
53697                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53698                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53699                         }
53700                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53701                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53702                         }
53703                         if (isMatchingConstructorReference(left_1)) {
53704                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53705                         }
53706                         if (isMatchingConstructorReference(right_1)) {
53707                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53708                         }
53709                         break;
53710                     case 98 /* InstanceOfKeyword */:
53711                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53712                     case 97 /* InKeyword */:
53713                         var target = getReferenceCandidate(expr.right);
53714                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53715                             return narrowByInKeyword(type, expr.left, assumeTrue);
53716                         }
53717                         break;
53718                     case 27 /* CommaToken */:
53719                         return narrowType(type, expr.right, assumeTrue);
53720                 }
53721                 return type;
53722             }
53723             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53724                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53725                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53726                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53727                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53728                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53729                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53730                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53731                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53732                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53733                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53734                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53735                 var valueType = getTypeOfExpression(value);
53736                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53737                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53738                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53739                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53740             }
53741             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53742                 if (type.flags & 1 /* Any */) {
53743                     return type;
53744                 }
53745                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53746                     assumeTrue = !assumeTrue;
53747                 }
53748                 var valueType = getTypeOfExpression(value);
53749                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53750                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53751                         return valueType;
53752                     }
53753                     if (valueType.flags & 524288 /* Object */) {
53754                         return nonPrimitiveType;
53755                     }
53756                     return type;
53757                 }
53758                 if (valueType.flags & 98304 /* Nullable */) {
53759                     if (!strictNullChecks) {
53760                         return type;
53761                     }
53762                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53763                     var facts = doubleEquals ?
53764                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53765                         valueType.flags & 65536 /* Null */ ?
53766                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53767                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53768                     return getTypeWithFacts(type, facts);
53769                 }
53770                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53771                     return type;
53772                 }
53773                 if (assumeTrue) {
53774                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53775                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53776                         function (t) { return areTypesComparable(t, valueType); };
53777                     var narrowedType = filterType(type, filterFn);
53778                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53779                 }
53780                 if (isUnitType(valueType)) {
53781                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53782                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53783                 }
53784                 return type;
53785             }
53786             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53787                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53788                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53789                     assumeTrue = !assumeTrue;
53790                 }
53791                 var target = getReferenceCandidate(typeOfExpr.expression);
53792                 if (!isMatchingReference(reference, target)) {
53793                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53794                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53795                     }
53796                     return type;
53797                 }
53798                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53799                     return type;
53800                 }
53801                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53802                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53803                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53804                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53805                         var expr = typeOfExpr.parent.parent;
53806                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53807                             return nonPrimitiveType;
53808                         }
53809                     }
53810                     return getUnionType([nonPrimitiveType, nullType]);
53811                 }
53812                 var facts = assumeTrue ?
53813                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53814                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53815                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53816                 function narrowTypeForTypeof(type) {
53817                     // We narrow a non-union type to an exact primitive type if the non-union type
53818                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53819                     // to one of the primitive types.
53820                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
53821                     if (targetType) {
53822                         if (isTypeSubtypeOf(type, targetType)) {
53823                             return type;
53824                         }
53825                         if (isTypeSubtypeOf(targetType, type)) {
53826                             return targetType;
53827                         }
53828                         if (type.flags & 63176704 /* Instantiable */) {
53829                             var constraint = getBaseConstraintOfType(type) || anyType;
53830                             if (isTypeSubtypeOf(targetType, constraint)) {
53831                                 return getIntersectionType([type, targetType]);
53832                             }
53833                         }
53834                     }
53835                     return type;
53836                 }
53837             }
53838             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
53839                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
53840                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53841             }
53842             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
53843                 // We only narrow if all case expressions specify
53844                 // values with unit types, except for the case where
53845                 // `type` is unknown. In this instance we map object
53846                 // types to the nonPrimitive type and narrow with that.
53847                 var switchTypes = getSwitchClauseTypes(switchStatement);
53848                 if (!switchTypes.length) {
53849                     return type;
53850                 }
53851                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
53852                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
53853                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
53854                     var groundClauseTypes = void 0;
53855                     for (var i = 0; i < clauseTypes.length; i += 1) {
53856                         var t = clauseTypes[i];
53857                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53858                             if (groundClauseTypes !== undefined) {
53859                                 groundClauseTypes.push(t);
53860                             }
53861                         }
53862                         else if (t.flags & 524288 /* Object */) {
53863                             if (groundClauseTypes === undefined) {
53864                                 groundClauseTypes = clauseTypes.slice(0, i);
53865                             }
53866                             groundClauseTypes.push(nonPrimitiveType);
53867                         }
53868                         else {
53869                             return type;
53870                         }
53871                     }
53872                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
53873                 }
53874                 var discriminantType = getUnionType(clauseTypes);
53875                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
53876                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
53877                 if (!hasDefaultClause) {
53878                     return caseType;
53879                 }
53880                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
53881                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
53882             }
53883             function getImpliedTypeFromTypeofCase(type, text) {
53884                 switch (text) {
53885                     case "function":
53886                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
53887                     case "object":
53888                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
53889                     default:
53890                         return typeofTypesByName.get(text) || type;
53891                 }
53892             }
53893             function narrowTypeForTypeofSwitch(candidate) {
53894                 return function (type) {
53895                     if (isTypeSubtypeOf(candidate, type)) {
53896                         return candidate;
53897                     }
53898                     if (type.flags & 63176704 /* Instantiable */) {
53899                         var constraint = getBaseConstraintOfType(type) || anyType;
53900                         if (isTypeSubtypeOf(candidate, constraint)) {
53901                             return getIntersectionType([type, candidate]);
53902                         }
53903                     }
53904                     return type;
53905                 };
53906             }
53907             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
53908                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
53909                 if (!switchWitnesses.length) {
53910                     return type;
53911                 }
53912                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
53913                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
53914                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
53915                 var clauseWitnesses;
53916                 var switchFacts;
53917                 if (defaultCaseLocation > -1) {
53918                     // We no longer need the undefined denoting an
53919                     // explicit default case. Remove the undefined and
53920                     // fix-up clauseStart and clauseEnd.  This means
53921                     // that we don't have to worry about undefined
53922                     // in the witness array.
53923                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
53924                     // The adjusted clause start and end after removing the `default` statement.
53925                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
53926                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
53927                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
53928                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
53929                 }
53930                 else {
53931                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
53932                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
53933                 }
53934                 if (hasDefaultClause) {
53935                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
53936                 }
53937                 /*
53938                   The implied type is the raw type suggested by a
53939                   value being caught in this clause.
53940
53941                   When the clause contains a default case we ignore
53942                   the implied type and try to narrow using any facts
53943                   we can learn: see `switchFacts`.
53944
53945                   Example:
53946                   switch (typeof x) {
53947                       case 'number':
53948                       case 'string': break;
53949                       default: break;
53950                       case 'number':
53951                       case 'boolean': break
53952                   }
53953
53954                   In the first clause (case `number` and `string`) the
53955                   implied type is number | string.
53956
53957                   In the default clause we de not compute an implied type.
53958
53959                   In the third clause (case `number` and `boolean`)
53960                   the naive implied type is number | boolean, however
53961                   we use the type facts to narrow the implied type to
53962                   boolean. We know that number cannot be selected
53963                   because it is caught in the first clause.
53964                 */
53965                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
53966                 if (impliedType.flags & 1048576 /* Union */) {
53967                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
53968                 }
53969                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
53970             }
53971             function isMatchingConstructorReference(expr) {
53972                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
53973                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
53974                     isMatchingReference(reference, expr.expression);
53975             }
53976             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
53977                 // Do not narrow when checking inequality.
53978                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
53979                     return type;
53980                 }
53981                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
53982                 var identifierType = getTypeOfExpression(identifier);
53983                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
53984                     return type;
53985                 }
53986                 // Get the prototype property of the type identifier so we can find out its type.
53987                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
53988                 if (!prototypeProperty) {
53989                     return type;
53990                 }
53991                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
53992                 var prototypeType = getTypeOfSymbol(prototypeProperty);
53993                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
53994                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
53995                     return type;
53996                 }
53997                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
53998                 if (isTypeAny(type)) {
53999                     return candidate;
54000                 }
54001                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54002                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54003                 function isConstructedBy(source, target) {
54004                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54005                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54006                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54007                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54008                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54009                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54010                         return source.symbol === target.symbol;
54011                     }
54012                     // For all other types just check that the `source` type is a subtype of the `target` type.
54013                     return isTypeSubtypeOf(source, target);
54014                 }
54015             }
54016             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54017                 var left = getReferenceCandidate(expr.left);
54018                 if (!isMatchingReference(reference, left)) {
54019                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54020                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54021                     }
54022                     return type;
54023                 }
54024                 // Check that right operand is a function type with a prototype property
54025                 var rightType = getTypeOfExpression(expr.right);
54026                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54027                     return type;
54028                 }
54029                 var targetType;
54030                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54031                 if (prototypeProperty) {
54032                     // Target type is type of the prototype property
54033                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54034                     if (!isTypeAny(prototypePropertyType)) {
54035                         targetType = prototypePropertyType;
54036                     }
54037                 }
54038                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54039                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54040                     return type;
54041                 }
54042                 if (!targetType) {
54043                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54044                     targetType = constructSignatures.length ?
54045                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54046                         emptyObjectType;
54047                 }
54048                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54049             }
54050             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54051                 if (!assumeTrue) {
54052                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54053                 }
54054                 // If the current type is a union type, remove all constituents that couldn't be instances of
54055                 // the candidate type. If one or more constituents remain, return a union of those.
54056                 if (type.flags & 1048576 /* Union */) {
54057                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54058                     if (!(assignableType.flags & 131072 /* Never */)) {
54059                         return assignableType;
54060                     }
54061                 }
54062                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54063                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54064                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54065                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54066                 // two types.
54067                 return isTypeSubtypeOf(candidate, type) ? candidate :
54068                     isTypeAssignableTo(type, candidate) ? type :
54069                         isTypeAssignableTo(candidate, type) ? candidate :
54070                             getIntersectionType([type, candidate]);
54071             }
54072             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54073                 if (hasMatchingArgument(callExpression, reference)) {
54074                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54075                     var predicate = signature && getTypePredicateOfSignature(signature);
54076                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54077                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54078                     }
54079                 }
54080                 return type;
54081             }
54082             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54083                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54084                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54085                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54086                     if (predicateArgument) {
54087                         if (isMatchingReference(reference, predicateArgument)) {
54088                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54089                         }
54090                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54091                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54092                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54093                         }
54094                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54095                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54096                         }
54097                     }
54098                 }
54099                 return type;
54100             }
54101             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54102             // will be a subtype or the same type as the argument.
54103             function narrowType(type, expr, assumeTrue) {
54104                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54105                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54106                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54107                     return narrowTypeByOptionality(type, expr, assumeTrue);
54108                 }
54109                 switch (expr.kind) {
54110                     case 75 /* Identifier */:
54111                     case 104 /* ThisKeyword */:
54112                     case 102 /* SuperKeyword */:
54113                     case 194 /* PropertyAccessExpression */:
54114                     case 195 /* ElementAccessExpression */:
54115                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54116                     case 196 /* CallExpression */:
54117                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54118                     case 200 /* ParenthesizedExpression */:
54119                         return narrowType(type, expr.expression, assumeTrue);
54120                     case 209 /* BinaryExpression */:
54121                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54122                     case 207 /* PrefixUnaryExpression */:
54123                         if (expr.operator === 53 /* ExclamationToken */) {
54124                             return narrowType(type, expr.operand, !assumeTrue);
54125                         }
54126                         break;
54127                 }
54128                 return type;
54129             }
54130             function narrowTypeByOptionality(type, expr, assumePresent) {
54131                 if (isMatchingReference(reference, expr)) {
54132                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54133                 }
54134                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54135                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54136                 }
54137                 return type;
54138             }
54139         }
54140         function getTypeOfSymbolAtLocation(symbol, location) {
54141             symbol = symbol.exportSymbol || symbol;
54142             // If we have an identifier or a property access at the given location, if the location is
54143             // an dotted name expression, and if the location is not an assignment target, obtain the type
54144             // of the expression (which will reflect control flow analysis). If the expression indeed
54145             // resolved to the given symbol, return the narrowed type.
54146             if (location.kind === 75 /* Identifier */) {
54147                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54148                     location = location.parent;
54149                 }
54150                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54151                     var type = getTypeOfExpression(location);
54152                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54153                         return type;
54154                     }
54155                 }
54156             }
54157             // The location isn't a reference to the given symbol, meaning we're being asked
54158             // a hypothetical question of what type the symbol would have if there was a reference
54159             // to it at the given location. Since we have no control flow information for the
54160             // hypothetical reference (control flow information is created and attached by the
54161             // binder), we simply return the declared type of the symbol.
54162             return getTypeOfSymbol(symbol);
54163         }
54164         function getControlFlowContainer(node) {
54165             return ts.findAncestor(node.parent, function (node) {
54166                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54167                     node.kind === 250 /* ModuleBlock */ ||
54168                     node.kind === 290 /* SourceFile */ ||
54169                     node.kind === 159 /* PropertyDeclaration */;
54170             });
54171         }
54172         // Check if a parameter is assigned anywhere within its declaring function.
54173         function isParameterAssigned(symbol) {
54174             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54175             var links = getNodeLinks(func);
54176             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54177                 links.flags |= 8388608 /* AssignmentsMarked */;
54178                 if (!hasParentWithAssignmentsMarked(func)) {
54179                     markParameterAssignments(func);
54180                 }
54181             }
54182             return symbol.isAssigned || false;
54183         }
54184         function hasParentWithAssignmentsMarked(node) {
54185             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54186         }
54187         function markParameterAssignments(node) {
54188             if (node.kind === 75 /* Identifier */) {
54189                 if (ts.isAssignmentTarget(node)) {
54190                     var symbol = getResolvedSymbol(node);
54191                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54192                         symbol.isAssigned = true;
54193                     }
54194                 }
54195             }
54196             else {
54197                 ts.forEachChild(node, markParameterAssignments);
54198             }
54199         }
54200         function isConstVariable(symbol) {
54201             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54202         }
54203         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54204         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54205             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54206                 var annotationIncludesUndefined = strictNullChecks &&
54207                     declaration.kind === 156 /* Parameter */ &&
54208                     declaration.initializer &&
54209                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54210                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54211                 popTypeResolution();
54212                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54213             }
54214             else {
54215                 reportCircularityError(declaration.symbol);
54216                 return declaredType;
54217             }
54218         }
54219         function isConstraintPosition(node) {
54220             var parent = node.parent;
54221             return parent.kind === 194 /* PropertyAccessExpression */ ||
54222                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54223                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54224                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54225         }
54226         function typeHasNullableConstraint(type) {
54227             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54228         }
54229         function getConstraintForLocation(type, node) {
54230             // When a node is the left hand expression of a property access, element access, or call expression,
54231             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54232             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54233             // the constraint type.
54234             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54235                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54236             }
54237             return type;
54238         }
54239         function isExportOrExportExpression(location) {
54240             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54241         }
54242         function markAliasReferenced(symbol, location) {
54243             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54244                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54245                     markAliasSymbolAsReferenced(symbol);
54246                 }
54247                 else {
54248                     markConstEnumAliasAsReferenced(symbol);
54249                 }
54250             }
54251         }
54252         function checkIdentifier(node) {
54253             var symbol = getResolvedSymbol(node);
54254             if (symbol === unknownSymbol) {
54255                 return errorType;
54256             }
54257             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54258             // Although in down-level emit of arrow function, we emit it using function expression which means that
54259             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54260             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54261             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54262             // can explicitly bound arguments objects
54263             if (symbol === argumentsSymbol) {
54264                 var container = ts.getContainingFunction(node);
54265                 if (languageVersion < 2 /* ES2015 */) {
54266                     if (container.kind === 202 /* ArrowFunction */) {
54267                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54268                     }
54269                     else if (ts.hasModifier(container, 256 /* Async */)) {
54270                         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);
54271                     }
54272                 }
54273                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54274                 return getTypeOfSymbol(symbol);
54275             }
54276             // We should only mark aliases as referenced if there isn't a local value declaration
54277             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54278             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54279                 markAliasReferenced(symbol, node);
54280             }
54281             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54282             var declaration = localOrExportSymbol.valueDeclaration;
54283             if (localOrExportSymbol.flags & 32 /* Class */) {
54284                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54285                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54286                 // behavior of class names in ES6.
54287                 if (declaration.kind === 245 /* ClassDeclaration */
54288                     && ts.nodeIsDecorated(declaration)) {
54289                     var container = ts.getContainingClass(node);
54290                     while (container !== undefined) {
54291                         if (container === declaration && container.name !== node) {
54292                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54293                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54294                             break;
54295                         }
54296                         container = ts.getContainingClass(container);
54297                     }
54298                 }
54299                 else if (declaration.kind === 214 /* ClassExpression */) {
54300                     // When we emit a class expression with static members that contain a reference
54301                     // to the constructor in the initializer, we will need to substitute that
54302                     // binding with an alias as the class name is not in scope.
54303                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54304                     while (container.kind !== 290 /* SourceFile */) {
54305                         if (container.parent === declaration) {
54306                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54307                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54308                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54309                             }
54310                             break;
54311                         }
54312                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54313                     }
54314                 }
54315             }
54316             checkNestedBlockScopedBinding(node, symbol);
54317             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54318             var assignmentKind = ts.getAssignmentTargetKind(node);
54319             if (assignmentKind) {
54320                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54321                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54322                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54323                     return errorType;
54324                 }
54325                 if (isReadonlySymbol(localOrExportSymbol)) {
54326                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54327                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54328                     }
54329                     else {
54330                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54331                     }
54332                     return errorType;
54333                 }
54334             }
54335             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54336             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54337             // entities we simply return the declared type.
54338             if (localOrExportSymbol.flags & 3 /* Variable */) {
54339                 if (assignmentKind === 1 /* Definite */) {
54340                     return type;
54341                 }
54342             }
54343             else if (isAlias) {
54344                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54345             }
54346             else {
54347                 return type;
54348             }
54349             if (!declaration) {
54350                 return type;
54351             }
54352             // The declaration container is the innermost function that encloses the declaration of the variable
54353             // or parameter. The flow container is the innermost function starting with which we analyze the control
54354             // flow graph to determine the control flow based type.
54355             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54356             var declarationContainer = getControlFlowContainer(declaration);
54357             var flowContainer = getControlFlowContainer(node);
54358             var isOuterVariable = flowContainer !== declarationContainer;
54359             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54360             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54361             // When the control flow originates in a function expression or arrow function and we are referencing
54362             // a const variable or parameter from an outer function, we extend the origin of the control flow
54363             // analysis to include the immediately enclosing function.
54364             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54365                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54366                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54367                 flowContainer = getControlFlowContainer(flowContainer);
54368             }
54369             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54370             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54371             // declaration container are the same).
54372             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54373                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54374                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54375                 node.parent.kind === 218 /* NonNullExpression */ ||
54376                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54377                 declaration.flags & 8388608 /* Ambient */;
54378             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54379                 type === autoType || type === autoArrayType ? undefinedType :
54380                     getOptionalType(type);
54381             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54382             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54383             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54384             // control flow based type does include undefined.
54385             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54386                 if (flowType === autoType || flowType === autoArrayType) {
54387                     if (noImplicitAny) {
54388                         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));
54389                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54390                     }
54391                     return convertAutoToAny(flowType);
54392                 }
54393             }
54394             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54395                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54396                 // Return the declared type to reduce follow-on errors
54397                 return type;
54398             }
54399             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54400         }
54401         function isInsideFunction(node, threshold) {
54402             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54403         }
54404         function getPartOfForStatementContainingNode(node, container) {
54405             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54406         }
54407         function checkNestedBlockScopedBinding(node, symbol) {
54408             if (languageVersion >= 2 /* ES2015 */ ||
54409                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54410                 ts.isSourceFile(symbol.valueDeclaration) ||
54411                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54412                 return;
54413             }
54414             // 1. walk from the use site up to the declaration and check
54415             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54416             // 2. walk from the declaration up to the boundary of lexical environment and check
54417             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54418             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54419             var usedInFunction = isInsideFunction(node.parent, container);
54420             var current = container;
54421             var containedInIterationStatement = false;
54422             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54423                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54424                     containedInIterationStatement = true;
54425                     break;
54426                 }
54427                 current = current.parent;
54428             }
54429             if (containedInIterationStatement) {
54430                 if (usedInFunction) {
54431                     // mark iteration statement as containing block-scoped binding captured in some function
54432                     var capturesBlockScopeBindingInLoopBody = true;
54433                     if (ts.isForStatement(container)) {
54434                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54435                         if (varDeclList && varDeclList.parent === container) {
54436                             var part = getPartOfForStatementContainingNode(node.parent, container);
54437                             if (part) {
54438                                 var links = getNodeLinks(part);
54439                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54440                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54441                                 ts.pushIfUnique(capturedBindings, symbol);
54442                                 if (part === container.initializer) {
54443                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54444                                 }
54445                             }
54446                         }
54447                     }
54448                     if (capturesBlockScopeBindingInLoopBody) {
54449                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54450                     }
54451                 }
54452                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54453                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54454                 if (ts.isForStatement(container)) {
54455                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54456                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54457                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54458                     }
54459                 }
54460                 // set 'declared inside loop' bit on the block-scoped binding
54461                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54462             }
54463             if (usedInFunction) {
54464                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54465             }
54466         }
54467         function isBindingCapturedByNode(node, decl) {
54468             var links = getNodeLinks(node);
54469             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54470         }
54471         function isAssignedInBodyOfForStatement(node, container) {
54472             // skip parenthesized nodes
54473             var current = node;
54474             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54475                 current = current.parent;
54476             }
54477             // check if node is used as LHS in some assignment expression
54478             var isAssigned = false;
54479             if (ts.isAssignmentTarget(current)) {
54480                 isAssigned = true;
54481             }
54482             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54483                 var expr = current.parent;
54484                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54485             }
54486             if (!isAssigned) {
54487                 return false;
54488             }
54489             // at this point we know that node is the target of assignment
54490             // now check that modification happens inside the statement part of the ForStatement
54491             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54492         }
54493         function captureLexicalThis(node, container) {
54494             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54495             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54496                 var classNode = container.parent;
54497                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54498             }
54499             else {
54500                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54501             }
54502         }
54503         function findFirstSuperCall(n) {
54504             if (ts.isSuperCall(n)) {
54505                 return n;
54506             }
54507             else if (ts.isFunctionLike(n)) {
54508                 return undefined;
54509             }
54510             return ts.forEachChild(n, findFirstSuperCall);
54511         }
54512         /**
54513          * Return a cached result if super-statement is already found.
54514          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54515          *
54516          * @param constructor constructor-function to look for super statement
54517          */
54518         function getSuperCallInConstructor(constructor) {
54519             var links = getNodeLinks(constructor);
54520             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54521             if (links.hasSuperCall === undefined) {
54522                 links.superCall = findFirstSuperCall(constructor.body);
54523                 links.hasSuperCall = links.superCall ? true : false;
54524             }
54525             return links.superCall;
54526         }
54527         /**
54528          * Check if the given class-declaration extends null then return true.
54529          * Otherwise, return false
54530          * @param classDecl a class declaration to check if it extends null
54531          */
54532         function classDeclarationExtendsNull(classDecl) {
54533             var classSymbol = getSymbolOfNode(classDecl);
54534             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54535             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54536             return baseConstructorType === nullWideningType;
54537         }
54538         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54539             var containingClassDecl = container.parent;
54540             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54541             // If a containing class does not have extends clause or the class extends null
54542             // skip checking whether super statement is called before "this" accessing.
54543             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54544                 var superCall = getSuperCallInConstructor(container);
54545                 // We should give an error in the following cases:
54546                 //      - No super-call
54547                 //      - "this" is accessing before super-call.
54548                 //          i.e super(this)
54549                 //              this.x; super();
54550                 // We want to make sure that super-call is done before accessing "this" so that
54551                 // "this" is not accessed as a parameter of the super-call.
54552                 if (!superCall || superCall.end > node.pos) {
54553                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54554                     error(node, diagnosticMessage);
54555                 }
54556             }
54557         }
54558         function checkThisExpression(node) {
54559             // Stop at the first arrow function so that we can
54560             // tell whether 'this' needs to be captured.
54561             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54562             var capturedByArrowFunction = false;
54563             if (container.kind === 162 /* Constructor */) {
54564                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54565             }
54566             // Now skip arrow functions to get the "real" owner of 'this'.
54567             if (container.kind === 202 /* ArrowFunction */) {
54568                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54569                 capturedByArrowFunction = true;
54570             }
54571             switch (container.kind) {
54572                 case 249 /* ModuleDeclaration */:
54573                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54574                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54575                     break;
54576                 case 248 /* EnumDeclaration */:
54577                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54578                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54579                     break;
54580                 case 162 /* Constructor */:
54581                     if (isInConstructorArgumentInitializer(node, container)) {
54582                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54583                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54584                     }
54585                     break;
54586                 case 159 /* PropertyDeclaration */:
54587                 case 158 /* PropertySignature */:
54588                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54589                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54590                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54591                     }
54592                     break;
54593                 case 154 /* ComputedPropertyName */:
54594                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54595                     break;
54596             }
54597             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54598             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54599                 captureLexicalThis(node, container);
54600             }
54601             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54602             if (noImplicitThis) {
54603                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54604                 if (type === globalThisType_1 && capturedByArrowFunction) {
54605                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54606                 }
54607                 else if (!type) {
54608                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54609                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54610                     if (!ts.isSourceFile(container)) {
54611                         var outsideThis = tryGetThisTypeAt(container);
54612                         if (outsideThis && outsideThis !== globalThisType_1) {
54613                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54614                         }
54615                     }
54616                 }
54617             }
54618             return type || anyType;
54619         }
54620         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54621             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54622             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54623             var isInJS = ts.isInJSFile(node);
54624             if (ts.isFunctionLike(container) &&
54625                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54626                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54627                 // If this is a function in a JS file, it might be a class method.
54628                 var className = getClassNameFromPrototypeMethod(container);
54629                 if (isInJS && className) {
54630                     var classSymbol = checkExpression(className).symbol;
54631                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54632                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54633                         if (classType) {
54634                             return getFlowTypeOfReference(node, classType);
54635                         }
54636                     }
54637                 }
54638                 // Check if it's a constructor definition, can be either a variable decl or function decl
54639                 // i.e.
54640                 //   * /** @constructor */ function [name]() { ... }
54641                 //   * /** @constructor */ var x = function() { ... }
54642                 else if (isInJS &&
54643                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54644                     ts.getJSDocClassTag(container)) {
54645                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54646                     return getFlowTypeOfReference(node, classType);
54647                 }
54648                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54649                 if (thisType) {
54650                     return getFlowTypeOfReference(node, thisType);
54651                 }
54652             }
54653             if (ts.isClassLike(container.parent)) {
54654                 var symbol = getSymbolOfNode(container.parent);
54655                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54656                 return getFlowTypeOfReference(node, type);
54657             }
54658             if (isInJS) {
54659                 var type = getTypeForThisExpressionFromJSDoc(container);
54660                 if (type && type !== errorType) {
54661                     return getFlowTypeOfReference(node, type);
54662                 }
54663             }
54664             if (ts.isSourceFile(container)) {
54665                 // look up in the source file's locals or exports
54666                 if (container.commonJsModuleIndicator) {
54667                     var fileSymbol = getSymbolOfNode(container);
54668                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54669                 }
54670                 else if (includeGlobalThis) {
54671                     return getTypeOfSymbol(globalThisSymbol);
54672                 }
54673             }
54674         }
54675         function getExplicitThisType(node) {
54676             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54677             if (ts.isFunctionLike(container)) {
54678                 var signature = getSignatureFromDeclaration(container);
54679                 if (signature.thisParameter) {
54680                     return getExplicitTypeOfSymbol(signature.thisParameter);
54681                 }
54682             }
54683             if (ts.isClassLike(container.parent)) {
54684                 var symbol = getSymbolOfNode(container.parent);
54685                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54686             }
54687         }
54688         function getClassNameFromPrototypeMethod(container) {
54689             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54690             if (container.kind === 201 /* FunctionExpression */ &&
54691                 ts.isBinaryExpression(container.parent) &&
54692                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54693                 // Get the 'x' of 'x.prototype.y = container'
54694                 return container.parent // x.prototype.y = container
54695                     .left // x.prototype.y
54696                     .expression // x.prototype
54697                     .expression; // x
54698             }
54699             // x.prototype = { method() { } }
54700             else if (container.kind === 161 /* MethodDeclaration */ &&
54701                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54702                 ts.isBinaryExpression(container.parent.parent) &&
54703                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54704                 return container.parent.parent.left.expression;
54705             }
54706             // x.prototype = { method: function() { } }
54707             else if (container.kind === 201 /* FunctionExpression */ &&
54708                 container.parent.kind === 281 /* PropertyAssignment */ &&
54709                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54710                 ts.isBinaryExpression(container.parent.parent.parent) &&
54711                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54712                 return container.parent.parent.parent.left.expression;
54713             }
54714             // Object.defineProperty(x, "method", { value: function() { } });
54715             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54716             // Object.defineProperty(x, "method", { get: () => function() { }) });
54717             else if (container.kind === 201 /* FunctionExpression */ &&
54718                 ts.isPropertyAssignment(container.parent) &&
54719                 ts.isIdentifier(container.parent.name) &&
54720                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54721                 ts.isObjectLiteralExpression(container.parent.parent) &&
54722                 ts.isCallExpression(container.parent.parent.parent) &&
54723                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54724                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54725                 return container.parent.parent.parent.arguments[0].expression;
54726             }
54727             // Object.defineProperty(x, "method", { value() { } });
54728             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54729             // Object.defineProperty(x, "method", { get() { return () => {} } });
54730             else if (ts.isMethodDeclaration(container) &&
54731                 ts.isIdentifier(container.name) &&
54732                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54733                 ts.isObjectLiteralExpression(container.parent) &&
54734                 ts.isCallExpression(container.parent.parent) &&
54735                 container.parent.parent.arguments[2] === container.parent &&
54736                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54737                 return container.parent.parent.arguments[0].expression;
54738             }
54739         }
54740         function getTypeForThisExpressionFromJSDoc(node) {
54741             var jsdocType = ts.getJSDocType(node);
54742             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54743                 var jsDocFunctionType = jsdocType;
54744                 if (jsDocFunctionType.parameters.length > 0 &&
54745                     jsDocFunctionType.parameters[0].name &&
54746                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54747                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54748                 }
54749             }
54750             var thisTag = ts.getJSDocThisTag(node);
54751             if (thisTag && thisTag.typeExpression) {
54752                 return getTypeFromTypeNode(thisTag.typeExpression);
54753             }
54754         }
54755         function isInConstructorArgumentInitializer(node, constructorDecl) {
54756             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54757         }
54758         function checkSuperExpression(node) {
54759             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54760             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54761             var needToCaptureLexicalThis = false;
54762             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54763             if (!isCallExpression) {
54764                 while (container && container.kind === 202 /* ArrowFunction */) {
54765                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54766                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54767                 }
54768             }
54769             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54770             var nodeCheckFlag = 0;
54771             if (!canUseSuperExpression) {
54772                 // issue more specific error if super is used in computed property name
54773                 // class A { foo() { return "1" }}
54774                 // class B {
54775                 //     [super.foo()]() {}
54776                 // }
54777                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54778                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54779                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54780                 }
54781                 else if (isCallExpression) {
54782                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54783                 }
54784                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54785                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54786                 }
54787                 else {
54788                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54789                 }
54790                 return errorType;
54791             }
54792             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54793                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54794             }
54795             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54796                 nodeCheckFlag = 512 /* SuperStatic */;
54797             }
54798             else {
54799                 nodeCheckFlag = 256 /* SuperInstance */;
54800             }
54801             getNodeLinks(node).flags |= nodeCheckFlag;
54802             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54803             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54804             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54805             // uses an arrow function, which is permitted to reference `super`.
54806             //
54807             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54808             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54809             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54810             //
54811             // The simplest case is reading a value, in which case we will emit something like the following:
54812             //
54813             //  // ts
54814             //  ...
54815             //  async asyncMethod() {
54816             //    let x = await super.asyncMethod();
54817             //    return x;
54818             //  }
54819             //  ...
54820             //
54821             //  // js
54822             //  ...
54823             //  asyncMethod() {
54824             //      const _super = Object.create(null, {
54825             //        asyncMethod: { get: () => super.asyncMethod },
54826             //      });
54827             //      return __awaiter(this, arguments, Promise, function *() {
54828             //          let x = yield _super.asyncMethod.call(this);
54829             //          return x;
54830             //      });
54831             //  }
54832             //  ...
54833             //
54834             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
54835             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
54836             //
54837             //  // ts
54838             //  ...
54839             //  async asyncMethod(ar: Promise<any[]>) {
54840             //      [super.a, super.b] = await ar;
54841             //  }
54842             //  ...
54843             //
54844             //  // js
54845             //  ...
54846             //  asyncMethod(ar) {
54847             //      const _super = Object.create(null, {
54848             //        a: { get: () => super.a, set: (v) => super.a = v },
54849             //        b: { get: () => super.b, set: (v) => super.b = v }
54850             //      };
54851             //      return __awaiter(this, arguments, Promise, function *() {
54852             //          [_super.a, _super.b] = yield ar;
54853             //      });
54854             //  }
54855             //  ...
54856             //
54857             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
54858             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
54859             //
54860             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
54861             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
54862                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
54863                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
54864                 }
54865                 else {
54866                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
54867                 }
54868             }
54869             if (needToCaptureLexicalThis) {
54870                 // call expressions are allowed only in constructors so they should always capture correct 'this'
54871                 // super property access expressions can also appear in arrow functions -
54872                 // in this case they should also use correct lexical this
54873                 captureLexicalThis(node.parent, container);
54874             }
54875             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
54876                 if (languageVersion < 2 /* ES2015 */) {
54877                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
54878                     return errorType;
54879                 }
54880                 else {
54881                     // for object literal assume that type of 'super' is 'any'
54882                     return anyType;
54883                 }
54884             }
54885             // at this point the only legal case for parent is ClassLikeDeclaration
54886             var classLikeDeclaration = container.parent;
54887             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
54888                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
54889                 return errorType;
54890             }
54891             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
54892             var baseClassType = classType && getBaseTypes(classType)[0];
54893             if (!baseClassType) {
54894                 return errorType;
54895             }
54896             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
54897                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
54898                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
54899                 return errorType;
54900             }
54901             return nodeCheckFlag === 512 /* SuperStatic */
54902                 ? getBaseConstructorTypeOfClass(classType)
54903                 : getTypeWithThisArgument(baseClassType, classType.thisType);
54904             function isLegalUsageOfSuperExpression(container) {
54905                 if (!container) {
54906                     return false;
54907                 }
54908                 if (isCallExpression) {
54909                     // TS 1.0 SPEC (April 2014): 4.8.1
54910                     // Super calls are only permitted in constructors of derived classes
54911                     return container.kind === 162 /* Constructor */;
54912                 }
54913                 else {
54914                     // TS 1.0 SPEC (April 2014)
54915                     // 'super' property access is allowed
54916                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
54917                     // - In a static member function or static member accessor
54918                     // topmost container must be something that is directly nested in the class declaration\object literal expression
54919                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
54920                         if (ts.hasModifier(container, 32 /* Static */)) {
54921                             return container.kind === 161 /* MethodDeclaration */ ||
54922                                 container.kind === 160 /* MethodSignature */ ||
54923                                 container.kind === 163 /* GetAccessor */ ||
54924                                 container.kind === 164 /* SetAccessor */;
54925                         }
54926                         else {
54927                             return container.kind === 161 /* MethodDeclaration */ ||
54928                                 container.kind === 160 /* MethodSignature */ ||
54929                                 container.kind === 163 /* GetAccessor */ ||
54930                                 container.kind === 164 /* SetAccessor */ ||
54931                                 container.kind === 159 /* PropertyDeclaration */ ||
54932                                 container.kind === 158 /* PropertySignature */ ||
54933                                 container.kind === 162 /* Constructor */;
54934                         }
54935                     }
54936                 }
54937                 return false;
54938             }
54939         }
54940         function getContainingObjectLiteral(func) {
54941             return (func.kind === 161 /* MethodDeclaration */ ||
54942                 func.kind === 163 /* GetAccessor */ ||
54943                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
54944                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
54945                     undefined;
54946         }
54947         function getThisTypeArgument(type) {
54948             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
54949         }
54950         function getThisTypeFromContextualType(type) {
54951             return mapType(type, function (t) {
54952                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
54953             });
54954         }
54955         function getContextualThisParameterType(func) {
54956             if (func.kind === 202 /* ArrowFunction */) {
54957                 return undefined;
54958             }
54959             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
54960                 var contextualSignature = getContextualSignature(func);
54961                 if (contextualSignature) {
54962                     var thisParameter = contextualSignature.thisParameter;
54963                     if (thisParameter) {
54964                         return getTypeOfSymbol(thisParameter);
54965                     }
54966                 }
54967             }
54968             var inJs = ts.isInJSFile(func);
54969             if (noImplicitThis || inJs) {
54970                 var containingLiteral = getContainingObjectLiteral(func);
54971                 if (containingLiteral) {
54972                     // We have an object literal method. Check if the containing object literal has a contextual type
54973                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
54974                     // any directly enclosing object literals.
54975                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
54976                     var literal = containingLiteral;
54977                     var type = contextualType;
54978                     while (type) {
54979                         var thisType = getThisTypeFromContextualType(type);
54980                         if (thisType) {
54981                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
54982                         }
54983                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
54984                             break;
54985                         }
54986                         literal = literal.parent.parent;
54987                         type = getApparentTypeOfContextualType(literal);
54988                     }
54989                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
54990                     // for 'this' is the non-null form of the contextual type for the containing object literal or
54991                     // the type of the object literal itself.
54992                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
54993                 }
54994                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
54995                 // contextual type for 'this' is 'obj'.
54996                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
54997                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
54998                     var target = parent.left;
54999                     if (ts.isAccessExpression(target)) {
55000                         var expression = target.expression;
55001                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55002                         if (inJs && ts.isIdentifier(expression)) {
55003                             var sourceFile = ts.getSourceFileOfNode(parent);
55004                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55005                                 return undefined;
55006                             }
55007                         }
55008                         return getWidenedType(checkExpressionCached(expression));
55009                     }
55010                 }
55011             }
55012             return undefined;
55013         }
55014         // Return contextual type of parameter or undefined if no contextual type is available
55015         function getContextuallyTypedParameterType(parameter) {
55016             var func = parameter.parent;
55017             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55018                 return undefined;
55019             }
55020             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55021             if (iife && iife.arguments) {
55022                 var args = getEffectiveCallArguments(iife);
55023                 var indexOfParameter = func.parameters.indexOf(parameter);
55024                 if (parameter.dotDotDotToken) {
55025                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55026                 }
55027                 var links = getNodeLinks(iife);
55028                 var cached = links.resolvedSignature;
55029                 links.resolvedSignature = anySignature;
55030                 var type = indexOfParameter < args.length ?
55031                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55032                     parameter.initializer ? undefined : undefinedWideningType;
55033                 links.resolvedSignature = cached;
55034                 return type;
55035             }
55036             var contextualSignature = getContextualSignature(func);
55037             if (contextualSignature) {
55038                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55039                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55040                     getRestTypeAtPosition(contextualSignature, index) :
55041                     tryGetTypeAtPosition(contextualSignature, index);
55042             }
55043         }
55044         function getContextualTypeForVariableLikeDeclaration(declaration) {
55045             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55046             if (typeNode) {
55047                 return getTypeFromTypeNode(typeNode);
55048             }
55049             switch (declaration.kind) {
55050                 case 156 /* Parameter */:
55051                     return getContextuallyTypedParameterType(declaration);
55052                 case 191 /* BindingElement */:
55053                     return getContextualTypeForBindingElement(declaration);
55054                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55055             }
55056         }
55057         function getContextualTypeForBindingElement(declaration) {
55058             var parent = declaration.parent.parent;
55059             var name = declaration.propertyName || declaration.name;
55060             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55061                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55062             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55063                 var nameType = getLiteralTypeFromPropertyName(name);
55064                 if (isTypeUsableAsPropertyName(nameType)) {
55065                     var text = getPropertyNameFromType(nameType);
55066                     return getTypeOfPropertyOfType(parentType, text);
55067                 }
55068             }
55069         }
55070         // In a variable, parameter or property declaration with a type annotation,
55071         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55072         // Otherwise, in a parameter declaration of a contextually typed function expression,
55073         //   the contextual type of an initializer expression is the contextual type of the parameter.
55074         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55075         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55076         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55077         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55078         function getContextualTypeForInitializerExpression(node) {
55079             var declaration = node.parent;
55080             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55081                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55082                 if (result) {
55083                     return result;
55084                 }
55085                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55086                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55087                 }
55088             }
55089             return undefined;
55090         }
55091         function getContextualTypeForReturnExpression(node) {
55092             var func = ts.getContainingFunction(node);
55093             if (func) {
55094                 var functionFlags = ts.getFunctionFlags(func);
55095                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55096                     return undefined;
55097                 }
55098                 var contextualReturnType = getContextualReturnType(func);
55099                 if (contextualReturnType) {
55100                     if (functionFlags & 2 /* Async */) { // Async function
55101                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55102                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55103                     }
55104                     return contextualReturnType; // Regular function
55105                 }
55106             }
55107             return undefined;
55108         }
55109         function getContextualTypeForAwaitOperand(node) {
55110             var contextualType = getContextualType(node);
55111             if (contextualType) {
55112                 var contextualAwaitedType = getAwaitedType(contextualType);
55113                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55114             }
55115             return undefined;
55116         }
55117         function getContextualTypeForYieldOperand(node) {
55118             var func = ts.getContainingFunction(node);
55119             if (func) {
55120                 var functionFlags = ts.getFunctionFlags(func);
55121                 var contextualReturnType = getContextualReturnType(func);
55122                 if (contextualReturnType) {
55123                     return node.asteriskToken
55124                         ? contextualReturnType
55125                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55126                 }
55127             }
55128             return undefined;
55129         }
55130         function isInParameterInitializerBeforeContainingFunction(node) {
55131             var inBindingInitializer = false;
55132             while (node.parent && !ts.isFunctionLike(node.parent)) {
55133                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55134                     return true;
55135                 }
55136                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55137                     inBindingInitializer = true;
55138                 }
55139                 node = node.parent;
55140             }
55141             return false;
55142         }
55143         function getContextualIterationType(kind, functionDecl) {
55144             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55145             var contextualReturnType = getContextualReturnType(functionDecl);
55146             if (contextualReturnType) {
55147                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55148                     || undefined;
55149             }
55150             return undefined;
55151         }
55152         function getContextualReturnType(functionDecl) {
55153             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55154             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55155             var returnType = getReturnTypeFromAnnotation(functionDecl);
55156             if (returnType) {
55157                 return returnType;
55158             }
55159             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55160             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55161             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55162             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55163                 return getReturnTypeOfSignature(signature);
55164             }
55165             return undefined;
55166         }
55167         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55168         function getContextualTypeForArgument(callTarget, arg) {
55169             var args = getEffectiveCallArguments(callTarget);
55170             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55171             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55172         }
55173         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55174             // If we're already in the process of resolving the given signature, don't resolve again as
55175             // that could cause infinite recursion. Instead, return anySignature.
55176             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55177             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55178                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55179             }
55180             return getTypeAtPosition(signature, argIndex);
55181         }
55182         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55183             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55184                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55185             }
55186             return undefined;
55187         }
55188         function getContextualTypeForBinaryOperand(node, contextFlags) {
55189             var binaryExpression = node.parent;
55190             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55191             switch (operatorToken.kind) {
55192                 case 62 /* EqualsToken */:
55193                     if (node !== right) {
55194                         return undefined;
55195                     }
55196                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55197                     if (!contextSensitive) {
55198                         return undefined;
55199                     }
55200                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55201                 case 56 /* BarBarToken */:
55202                 case 60 /* QuestionQuestionToken */:
55203                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55204                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55205                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55206                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55207                     // `namespace.prop = namespace.prop || {}`.
55208                     var type = getContextualType(binaryExpression, contextFlags);
55209                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55210                         getTypeOfExpression(left) : type;
55211                 case 55 /* AmpersandAmpersandToken */:
55212                 case 27 /* CommaToken */:
55213                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55214                 default:
55215                     return undefined;
55216             }
55217         }
55218         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55219         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55220         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55221             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55222             switch (kind) {
55223                 case 0 /* None */:
55224                     return true;
55225                 case 5 /* Property */:
55226                 case 1 /* ExportsProperty */:
55227                 case 6 /* Prototype */:
55228                 case 3 /* PrototypeProperty */:
55229                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55230                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55231                     if (!binaryExpression.left.symbol) {
55232                         return true;
55233                     }
55234                     else {
55235                         var decl = binaryExpression.left.symbol.valueDeclaration;
55236                         if (!decl) {
55237                             return false;
55238                         }
55239                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55240                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55241                         if (overallAnnotation) {
55242                             return getTypeFromTypeNode(overallAnnotation);
55243                         }
55244                         else if (ts.isIdentifier(lhs.expression)) {
55245                             var id = lhs.expression;
55246                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55247                             if (parentSymbol) {
55248                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55249                                 if (annotated) {
55250                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55251                                     if (nameStr_1 !== undefined) {
55252                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55253                                         return type || false;
55254                                     }
55255                                 }
55256                                 return false;
55257                             }
55258                         }
55259                         return !ts.isInJSFile(decl);
55260                     }
55261                 case 2 /* ModuleExports */:
55262                 case 4 /* ThisProperty */:
55263                     if (!binaryExpression.symbol)
55264                         return true;
55265                     if (binaryExpression.symbol.valueDeclaration) {
55266                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55267                         if (annotated) {
55268                             var type = getTypeFromTypeNode(annotated);
55269                             if (type) {
55270                                 return type;
55271                             }
55272                         }
55273                     }
55274                     if (kind === 2 /* ModuleExports */)
55275                         return false;
55276                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55277                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55278                         return false;
55279                     }
55280                     var thisType = checkThisExpression(thisAccess.expression);
55281                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55282                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55283                 case 7 /* ObjectDefinePropertyValue */:
55284                 case 8 /* ObjectDefinePropertyExports */:
55285                 case 9 /* ObjectDefinePrototypeProperty */:
55286                     return ts.Debug.fail("Does not apply");
55287                 default:
55288                     return ts.Debug.assertNever(kind);
55289             }
55290         }
55291         function getTypeOfPropertyOfContextualType(type, name) {
55292             return mapType(type, function (t) {
55293                 if (isGenericMappedType(t)) {
55294                     var constraint = getConstraintTypeFromMappedType(t);
55295                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55296                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55297                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55298                         return substituteIndexedMappedType(t, propertyNameType);
55299                     }
55300                 }
55301                 else if (t.flags & 3670016 /* StructuredType */) {
55302                     var prop = getPropertyOfType(t, name);
55303                     if (prop) {
55304                         return getTypeOfSymbol(prop);
55305                     }
55306                     if (isTupleType(t)) {
55307                         var restType = getRestTypeOfTupleType(t);
55308                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55309                             return restType;
55310                         }
55311                     }
55312                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55313                         getIndexTypeOfContextualType(t, 0 /* String */);
55314                 }
55315                 return undefined;
55316             }, /*noReductions*/ true);
55317         }
55318         function getIndexTypeOfContextualType(type, kind) {
55319             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55320         }
55321         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55322         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55323         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55324         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55325             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55326             if (node.flags & 16777216 /* InWithStatement */) {
55327                 // We cannot answer semantic questions within a with block, do not proceed any further
55328                 return undefined;
55329             }
55330             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55331         }
55332         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55333             var objectLiteral = element.parent;
55334             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55335             if (type) {
55336                 if (!hasNonBindableDynamicName(element)) {
55337                     // For a (non-symbol) computed property, there is no reason to look up the name
55338                     // in the type. It will just be "__computed", which does not appear in any
55339                     // SymbolTable.
55340                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55341                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55342                     if (propertyType) {
55343                         return propertyType;
55344                     }
55345                 }
55346                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55347                     getIndexTypeOfContextualType(type, 0 /* String */);
55348             }
55349             return undefined;
55350         }
55351         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55352         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55353         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55354         // type of T.
55355         function getContextualTypeForElementExpression(arrayContextualType, index) {
55356             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55357                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55358         }
55359         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55360         function getContextualTypeForConditionalOperand(node, contextFlags) {
55361             var conditional = node.parent;
55362             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55363         }
55364         function getContextualTypeForChildJsxExpression(node, child) {
55365             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55366             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55367             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55368             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55369                 return undefined;
55370             }
55371             var realChildren = getSemanticJsxChildren(node.children);
55372             var childIndex = realChildren.indexOf(child);
55373             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55374             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55375                 if (isArrayLikeType(t)) {
55376                     return getIndexedAccessType(t, getLiteralType(childIndex));
55377                 }
55378                 else {
55379                     return t;
55380                 }
55381             }, /*noReductions*/ true));
55382         }
55383         function getContextualTypeForJsxExpression(node) {
55384             var exprParent = node.parent;
55385             return ts.isJsxAttributeLike(exprParent)
55386                 ? getContextualType(node)
55387                 : ts.isJsxElement(exprParent)
55388                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55389                     : undefined;
55390         }
55391         function getContextualTypeForJsxAttribute(attribute) {
55392             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55393             // which is a type of the parameter of the signature we are trying out.
55394             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55395             if (ts.isJsxAttribute(attribute)) {
55396                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55397                 if (!attributesType || isTypeAny(attributesType)) {
55398                     return undefined;
55399                 }
55400                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55401             }
55402             else {
55403                 return getContextualType(attribute.parent);
55404             }
55405         }
55406         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55407         // expressions we check to those that don't depend on their contextual type in order not to cause
55408         // recursive (and possibly infinite) invocations of getContextualType.
55409         function isPossiblyDiscriminantValue(node) {
55410             switch (node.kind) {
55411                 case 10 /* StringLiteral */:
55412                 case 8 /* NumericLiteral */:
55413                 case 9 /* BigIntLiteral */:
55414                 case 14 /* NoSubstitutionTemplateLiteral */:
55415                 case 106 /* TrueKeyword */:
55416                 case 91 /* FalseKeyword */:
55417                 case 100 /* NullKeyword */:
55418                 case 75 /* Identifier */:
55419                 case 146 /* UndefinedKeyword */:
55420                     return true;
55421                 case 194 /* PropertyAccessExpression */:
55422                 case 200 /* ParenthesizedExpression */:
55423                     return isPossiblyDiscriminantValue(node.expression);
55424                 case 276 /* JsxExpression */:
55425                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55426             }
55427             return false;
55428         }
55429         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55430             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);
55431         }
55432         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55433             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);
55434         }
55435         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55436         // be "pushed" onto a node using the contextualType property.
55437         function getApparentTypeOfContextualType(node, contextFlags) {
55438             var contextualType = ts.isObjectLiteralMethod(node) ?
55439                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55440                 getContextualType(node, contextFlags);
55441             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55442             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55443                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55444                 if (apparentType.flags & 1048576 /* Union */) {
55445                     if (ts.isObjectLiteralExpression(node)) {
55446                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55447                     }
55448                     else if (ts.isJsxAttributes(node)) {
55449                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55450                     }
55451                 }
55452                 return apparentType;
55453             }
55454         }
55455         // If the given contextual type contains instantiable types and if a mapper representing
55456         // return type inferences is available, instantiate those types using that mapper.
55457         function instantiateContextualType(contextualType, node, contextFlags) {
55458             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55459                 var inferenceContext = getInferenceContext(node);
55460                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55461                 // would just be replaced with their defaults similar to the apparent type.
55462                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55463                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55464                     // types as well as arguments to the left in a function call.
55465                     if (contextFlags && contextFlags & 1 /* Signature */) {
55466                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55467                     }
55468                     // For other purposes (e.g. determining whether to produce literal types) we only
55469                     // incorporate inferences made from the return type in a function call.
55470                     if (inferenceContext.returnMapper) {
55471                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55472                     }
55473                 }
55474             }
55475             return contextualType;
55476         }
55477         // This function is similar to instantiateType, except that (a) it only instantiates types that
55478         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55479         // no reductions on instantiated union types.
55480         function instantiateInstantiableTypes(type, mapper) {
55481             if (type.flags & 63176704 /* Instantiable */) {
55482                 return instantiateType(type, mapper);
55483             }
55484             if (type.flags & 1048576 /* Union */) {
55485                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55486             }
55487             if (type.flags & 2097152 /* Intersection */) {
55488                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55489             }
55490             return type;
55491         }
55492         /**
55493          * Whoa! Do you really want to use this function?
55494          *
55495          * Unless you're trying to get the *non-apparent* type for a
55496          * value-literal type or you're authoring relevant portions of this algorithm,
55497          * you probably meant to use 'getApparentTypeOfContextualType'.
55498          * Otherwise this may not be very useful.
55499          *
55500          * In cases where you *are* working on this function, you should understand
55501          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55502          *
55503          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55504          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55505          *
55506          * @param node the expression whose contextual type will be returned.
55507          * @returns the contextual type of an expression.
55508          */
55509         function getContextualType(node, contextFlags) {
55510             if (node.flags & 16777216 /* InWithStatement */) {
55511                 // We cannot answer semantic questions within a with block, do not proceed any further
55512                 return undefined;
55513             }
55514             if (node.contextualType) {
55515                 return node.contextualType;
55516             }
55517             var parent = node.parent;
55518             switch (parent.kind) {
55519                 case 242 /* VariableDeclaration */:
55520                 case 156 /* Parameter */:
55521                 case 159 /* PropertyDeclaration */:
55522                 case 158 /* PropertySignature */:
55523                 case 191 /* BindingElement */:
55524                     return getContextualTypeForInitializerExpression(node);
55525                 case 202 /* ArrowFunction */:
55526                 case 235 /* ReturnStatement */:
55527                     return getContextualTypeForReturnExpression(node);
55528                 case 212 /* YieldExpression */:
55529                     return getContextualTypeForYieldOperand(parent);
55530                 case 206 /* AwaitExpression */:
55531                     return getContextualTypeForAwaitOperand(parent);
55532                 case 196 /* CallExpression */:
55533                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55534                         return stringType;
55535                     }
55536                 /* falls through */
55537                 case 197 /* NewExpression */:
55538                     return getContextualTypeForArgument(parent, node);
55539                 case 199 /* TypeAssertionExpression */:
55540                 case 217 /* AsExpression */:
55541                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55542                 case 209 /* BinaryExpression */:
55543                     return getContextualTypeForBinaryOperand(node, contextFlags);
55544                 case 281 /* PropertyAssignment */:
55545                 case 282 /* ShorthandPropertyAssignment */:
55546                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55547                 case 283 /* SpreadAssignment */:
55548                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55549                 case 192 /* ArrayLiteralExpression */: {
55550                     var arrayLiteral = parent;
55551                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55552                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55553                 }
55554                 case 210 /* ConditionalExpression */:
55555                     return getContextualTypeForConditionalOperand(node, contextFlags);
55556                 case 221 /* TemplateSpan */:
55557                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55558                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55559                 case 200 /* ParenthesizedExpression */: {
55560                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55561                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55562                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55563                 }
55564                 case 276 /* JsxExpression */:
55565                     return getContextualTypeForJsxExpression(parent);
55566                 case 273 /* JsxAttribute */:
55567                 case 275 /* JsxSpreadAttribute */:
55568                     return getContextualTypeForJsxAttribute(parent);
55569                 case 268 /* JsxOpeningElement */:
55570                 case 267 /* JsxSelfClosingElement */:
55571                     return getContextualJsxElementAttributesType(parent, contextFlags);
55572             }
55573             return undefined;
55574         }
55575         function getInferenceContext(node) {
55576             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55577             return ancestor && ancestor.inferenceContext;
55578         }
55579         function getContextualJsxElementAttributesType(node, contextFlags) {
55580             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55581                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55582                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55583                 // (as below) instead!
55584                 return node.parent.contextualType;
55585             }
55586             return getContextualTypeForArgumentAtIndex(node, 0);
55587         }
55588         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55589             return getJsxReferenceKind(node) !== 0 /* Component */
55590                 ? getJsxPropsTypeFromCallSignature(signature, node)
55591                 : getJsxPropsTypeFromClassType(signature, node);
55592         }
55593         function getJsxPropsTypeFromCallSignature(sig, context) {
55594             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55595             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55596             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55597             if (intrinsicAttribs !== errorType) {
55598                 propsType = intersectTypes(intrinsicAttribs, propsType);
55599             }
55600             return propsType;
55601         }
55602         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55603             if (sig.unionSignatures) {
55604                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55605                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55606                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55607                 // 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.
55608                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55609                 var results = [];
55610                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55611                     var signature = _a[_i];
55612                     var instance = getReturnTypeOfSignature(signature);
55613                     if (isTypeAny(instance)) {
55614                         return instance;
55615                     }
55616                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55617                     if (!propType) {
55618                         return;
55619                     }
55620                     results.push(propType);
55621                 }
55622                 return getIntersectionType(results);
55623             }
55624             var instanceType = getReturnTypeOfSignature(sig);
55625             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55626         }
55627         function getStaticTypeOfReferencedJsxConstructor(context) {
55628             if (isJsxIntrinsicIdentifier(context.tagName)) {
55629                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55630                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55631                 return getOrCreateTypeFromSignature(fakeSignature);
55632             }
55633             var tagType = checkExpressionCached(context.tagName);
55634             if (tagType.flags & 128 /* StringLiteral */) {
55635                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55636                 if (!result) {
55637                     return errorType;
55638                 }
55639                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55640                 return getOrCreateTypeFromSignature(fakeSignature);
55641             }
55642             return tagType;
55643         }
55644         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55645             var managedSym = getJsxLibraryManagedAttributes(ns);
55646             if (managedSym) {
55647                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55648                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55649                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55650                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55651                     return createTypeReference(declaredManagedType, args);
55652                 }
55653                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55654                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55655                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55656                 }
55657             }
55658             return attributesType;
55659         }
55660         function getJsxPropsTypeFromClassType(sig, context) {
55661             var ns = getJsxNamespaceAt(context);
55662             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55663             var attributesType = forcedLookupLocation === undefined
55664                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55665                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55666                 : forcedLookupLocation === ""
55667                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55668                     ? getReturnTypeOfSignature(sig)
55669                     // Otherwise get the type of the property on the signature return type
55670                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55671             if (!attributesType) {
55672                 // There is no property named 'props' on this instance type
55673                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55674                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55675                 }
55676                 return unknownType;
55677             }
55678             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55679             if (isTypeAny(attributesType)) {
55680                 // Props is of type 'any' or unknown
55681                 return attributesType;
55682             }
55683             else {
55684                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55685                 var apparentAttributesType = attributesType;
55686                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55687                 if (intrinsicClassAttribs !== errorType) {
55688                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55689                     var hostClassType = getReturnTypeOfSignature(sig);
55690                     apparentAttributesType = intersectTypes(typeParams
55691                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55692                         : intrinsicClassAttribs, apparentAttributesType);
55693                 }
55694                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55695                 if (intrinsicAttribs !== errorType) {
55696                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55697                 }
55698                 return apparentAttributesType;
55699             }
55700         }
55701         // If the given type is an object or union type with a single signature, and if that signature has at
55702         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55703         function getContextualCallSignature(type, node) {
55704             var signatures = getSignaturesOfType(type, 0 /* Call */);
55705             if (signatures.length === 1) {
55706                 var signature = signatures[0];
55707                 if (!isAritySmaller(signature, node)) {
55708                     return signature;
55709                 }
55710             }
55711         }
55712         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55713         function isAritySmaller(signature, target) {
55714             var targetParameterCount = 0;
55715             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55716                 var param = target.parameters[targetParameterCount];
55717                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55718                     break;
55719                 }
55720             }
55721             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55722                 targetParameterCount--;
55723             }
55724             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55725         }
55726         function isFunctionExpressionOrArrowFunction(node) {
55727             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55728         }
55729         function getContextualSignatureForFunctionLikeDeclaration(node) {
55730             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55731             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55732                 ? getContextualSignature(node)
55733                 : undefined;
55734         }
55735         // Return the contextual signature for a given expression node. A contextual type provides a
55736         // contextual signature if it has a single call signature and if that call signature is non-generic.
55737         // If the contextual type is a union type, get the signature from each type possible and if they are
55738         // all identical ignoring their return type, the result is same signature but with return type as
55739         // union type of return types from these signatures
55740         function getContextualSignature(node) {
55741             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55742             var typeTagSignature = getSignatureOfTypeTag(node);
55743             if (typeTagSignature) {
55744                 return typeTagSignature;
55745             }
55746             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55747             if (!type) {
55748                 return undefined;
55749             }
55750             if (!(type.flags & 1048576 /* Union */)) {
55751                 return getContextualCallSignature(type, node);
55752             }
55753             var signatureList;
55754             var types = type.types;
55755             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55756                 var current = types_17[_i];
55757                 var signature = getContextualCallSignature(current, node);
55758                 if (signature) {
55759                     if (!signatureList) {
55760                         // This signature will contribute to contextual union signature
55761                         signatureList = [signature];
55762                     }
55763                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55764                         // Signatures aren't identical, do not use
55765                         return undefined;
55766                     }
55767                     else {
55768                         // Use this signature for contextual union signature
55769                         signatureList.push(signature);
55770                     }
55771                 }
55772             }
55773             // Result is union of signatures collected (return type is union of return types of this signature set)
55774             if (signatureList) {
55775                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55776             }
55777         }
55778         function checkSpreadExpression(node, checkMode) {
55779             if (languageVersion < 2 /* ES2015 */) {
55780                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55781             }
55782             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55783             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55784         }
55785         function hasDefaultValue(node) {
55786             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55787                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55788         }
55789         function checkArrayLiteral(node, checkMode, forceTuple) {
55790             var elements = node.elements;
55791             var elementCount = elements.length;
55792             var elementTypes = [];
55793             var hasEndingSpreadElement = false;
55794             var hasNonEndingSpreadElement = false;
55795             var contextualType = getApparentTypeOfContextualType(node);
55796             var inDestructuringPattern = ts.isAssignmentTarget(node);
55797             var inConstContext = isConstContext(node);
55798             for (var i = 0; i < elementCount; i++) {
55799                 var e = elements[i];
55800                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55801                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55802                 if (spreadType && isTupleType(spreadType)) {
55803                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55804                     if (spreadType.target.hasRestElement) {
55805                         if (i === elementCount - 1)
55806                             hasEndingSpreadElement = true;
55807                         else
55808                             hasNonEndingSpreadElement = true;
55809                     }
55810                 }
55811                 else {
55812                     if (inDestructuringPattern && spreadType) {
55813                         // Given the following situation:
55814                         //    var c: {};
55815                         //    [...c] = ["", 0];
55816                         //
55817                         // c is represented in the tree as a spread element in an array literal.
55818                         // But c really functions as a rest element, and its purpose is to provide
55819                         // a contextual type for the right hand side of the assignment. Therefore,
55820                         // instead of calling checkExpression on "...c", which will give an error
55821                         // if c is not iterable/array-like, we need to act as if we are trying to
55822                         // get the contextual element type from it. So we do something similar to
55823                         // getContextualTypeForElementExpression, which will crucially not error
55824                         // if there is no index type / iterated type.
55825                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
55826                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
55827                         if (restElementType) {
55828                             elementTypes.push(restElementType);
55829                         }
55830                     }
55831                     else {
55832                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
55833                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
55834                         elementTypes.push(type);
55835                     }
55836                     if (spread) { // tuples are done above, so these are only arrays
55837                         if (i === elementCount - 1)
55838                             hasEndingSpreadElement = true;
55839                         else
55840                             hasNonEndingSpreadElement = true;
55841                     }
55842                 }
55843             }
55844             if (!hasNonEndingSpreadElement) {
55845                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
55846                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
55847                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
55848                 var tupleResult = void 0;
55849                 if (inDestructuringPattern && minLength > 0) {
55850                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55851                     type.pattern = node;
55852                     return type;
55853                 }
55854                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
55855                     return createArrayLiteralType(tupleResult);
55856                 }
55857                 else if (forceTuple) {
55858                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55859                 }
55860             }
55861             return createArrayLiteralType(createArrayType(elementTypes.length ?
55862                 getUnionType(elementTypes, 2 /* Subtype */) :
55863                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
55864         }
55865         function createArrayLiteralType(type) {
55866             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
55867                 return type;
55868             }
55869             var literalType = type.literalType;
55870             if (!literalType) {
55871                 literalType = type.literalType = cloneTypeReference(type);
55872                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
55873             }
55874             return literalType;
55875         }
55876         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
55877             if (elementCount === void 0) { elementCount = elementTypes.length; }
55878             if (readonly === void 0) { readonly = false; }
55879             // Infer a tuple type when the contextual type is or contains a tuple-like type
55880             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
55881                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
55882             }
55883         }
55884         function isNumericName(name) {
55885             switch (name.kind) {
55886                 case 154 /* ComputedPropertyName */:
55887                     return isNumericComputedName(name);
55888                 case 75 /* Identifier */:
55889                     return isNumericLiteralName(name.escapedText);
55890                 case 8 /* NumericLiteral */:
55891                 case 10 /* StringLiteral */:
55892                     return isNumericLiteralName(name.text);
55893                 default:
55894                     return false;
55895             }
55896         }
55897         function isNumericComputedName(name) {
55898             // It seems odd to consider an expression of type Any to result in a numeric name,
55899             // but this behavior is consistent with checkIndexedAccess
55900             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
55901         }
55902         function isInfinityOrNaNString(name) {
55903             return name === "Infinity" || name === "-Infinity" || name === "NaN";
55904         }
55905         function isNumericLiteralName(name) {
55906             // The intent of numeric names is that
55907             //     - they are names with text in a numeric form, and that
55908             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
55909             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
55910             //
55911             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
55912             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
55913             //
55914             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
55915             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
55916             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
55917             // because their 'ToString' representation is not equal to their original text.
55918             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
55919             //
55920             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
55921             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
55922             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
55923             //
55924             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
55925             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
55926             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
55927             return (+name).toString() === name;
55928         }
55929         function checkComputedPropertyName(node) {
55930             var links = getNodeLinks(node.expression);
55931             if (!links.resolvedType) {
55932                 links.resolvedType = checkExpression(node.expression);
55933                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
55934                 // type, and any union of these types (like string | number).
55935                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
55936                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
55937                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
55938                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
55939                 }
55940                 else {
55941                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
55942                 }
55943             }
55944             return links.resolvedType;
55945         }
55946         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
55947             var propTypes = [];
55948             for (var i = 0; i < properties.length; i++) {
55949                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
55950                     propTypes.push(getTypeOfSymbol(properties[i]));
55951                 }
55952             }
55953             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
55954             return createIndexInfo(unionType, isConstContext(node));
55955         }
55956         function getImmediateAliasedSymbol(symbol) {
55957             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
55958             var links = getSymbolLinks(symbol);
55959             if (!links.immediateTarget) {
55960                 var node = getDeclarationOfAliasSymbol(symbol);
55961                 if (!node)
55962                     return ts.Debug.fail();
55963                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
55964             }
55965             return links.immediateTarget;
55966         }
55967         function checkObjectLiteral(node, checkMode) {
55968             var inDestructuringPattern = ts.isAssignmentTarget(node);
55969             // Grammar checking
55970             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
55971             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
55972             var propertiesTable = ts.createSymbolTable();
55973             var propertiesArray = [];
55974             var spread = emptyObjectType;
55975             var contextualType = getApparentTypeOfContextualType(node);
55976             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
55977                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
55978             var inConstContext = isConstContext(node);
55979             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
55980             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
55981             var enumTag = ts.getJSDocEnumTag(node);
55982             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
55983             var objectFlags = freshObjectLiteralFlag;
55984             var patternWithComputedProperties = false;
55985             var hasComputedStringProperty = false;
55986             var hasComputedNumberProperty = false;
55987             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
55988             // As otherwise they may not be checked until exports for the type at this position are retrieved,
55989             // which may never occur.
55990             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
55991                 var elem = _a[_i];
55992                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
55993                     checkComputedPropertyName(elem.name);
55994                 }
55995             }
55996             var offset = 0;
55997             for (var i = 0; i < node.properties.length; i++) {
55998                 var memberDecl = node.properties[i];
55999                 var member = getSymbolOfNode(memberDecl);
56000                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56001                     checkComputedPropertyName(memberDecl.name) : undefined;
56002                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56003                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56004                     ts.isObjectLiteralMethod(memberDecl)) {
56005                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56006                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56007                             checkObjectLiteralMethod(memberDecl, checkMode);
56008                     if (isInJavascript) {
56009                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56010                         if (jsDocType) {
56011                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56012                             type = jsDocType;
56013                         }
56014                         else if (enumTag && enumTag.typeExpression) {
56015                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56016                         }
56017                     }
56018                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56019                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56020                     var prop = nameType ?
56021                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56022                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56023                     if (nameType) {
56024                         prop.nameType = nameType;
56025                     }
56026                     if (inDestructuringPattern) {
56027                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56028                         // for the property, make the property optional.
56029                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56030                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56031                         if (isOptional) {
56032                             prop.flags |= 16777216 /* Optional */;
56033                         }
56034                     }
56035                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56036                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56037                         // binding pattern specifies a default value for the property, make the property optional.
56038                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56039                         if (impliedProp) {
56040                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56041                         }
56042                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56043                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56044                         }
56045                     }
56046                     prop.declarations = member.declarations;
56047                     prop.parent = member.parent;
56048                     if (member.valueDeclaration) {
56049                         prop.valueDeclaration = member.valueDeclaration;
56050                     }
56051                     prop.type = type;
56052                     prop.target = member;
56053                     member = prop;
56054                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56055                 }
56056                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56057                     if (languageVersion < 2 /* ES2015 */) {
56058                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56059                     }
56060                     if (propertiesArray.length > 0) {
56061                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56062                         propertiesArray = [];
56063                         propertiesTable = ts.createSymbolTable();
56064                         hasComputedStringProperty = false;
56065                         hasComputedNumberProperty = false;
56066                     }
56067                     var type = getReducedType(checkExpression(memberDecl.expression));
56068                     if (!isValidSpreadType(type)) {
56069                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56070                         return errorType;
56071                     }
56072                     if (allPropertiesTable) {
56073                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56074                     }
56075                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56076                     offset = i + 1;
56077                     continue;
56078                 }
56079                 else {
56080                     // TypeScript 1.0 spec (April 2014)
56081                     // A get accessor declaration is processed in the same manner as
56082                     // an ordinary function declaration(section 6.1) with no parameters.
56083                     // A set accessor declaration is processed in the same manner
56084                     // as an ordinary function declaration with a single parameter and a Void return type.
56085                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56086                     checkNodeDeferred(memberDecl);
56087                 }
56088                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56089                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56090                         if (isTypeAssignableTo(computedNameType, numberType)) {
56091                             hasComputedNumberProperty = true;
56092                         }
56093                         else {
56094                             hasComputedStringProperty = true;
56095                         }
56096                         if (inDestructuringPattern) {
56097                             patternWithComputedProperties = true;
56098                         }
56099                     }
56100                 }
56101                 else {
56102                     propertiesTable.set(member.escapedName, member);
56103                 }
56104                 propertiesArray.push(member);
56105             }
56106             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56107             // type with those properties for which the binding pattern specifies a default value.
56108             // If the object literal is spread into another object literal, skip this step and let the top-level object
56109             // literal handle it instead.
56110             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56111                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56112                     var prop = _c[_b];
56113                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56114                         if (!(prop.flags & 16777216 /* Optional */)) {
56115                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56116                         }
56117                         propertiesTable.set(prop.escapedName, prop);
56118                         propertiesArray.push(prop);
56119                     }
56120                 }
56121             }
56122             if (spread !== emptyObjectType) {
56123                 if (propertiesArray.length > 0) {
56124                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56125                     propertiesArray = [];
56126                     propertiesTable = ts.createSymbolTable();
56127                     hasComputedStringProperty = false;
56128                     hasComputedNumberProperty = false;
56129                 }
56130                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56131                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56132             }
56133             return createObjectLiteralType();
56134             function createObjectLiteralType() {
56135                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56136                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56137                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56138                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56139                 if (isJSObjectLiteral) {
56140                     result.objectFlags |= 16384 /* JSLiteral */;
56141                 }
56142                 if (patternWithComputedProperties) {
56143                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56144                 }
56145                 if (inDestructuringPattern) {
56146                     result.pattern = node;
56147                 }
56148                 return result;
56149             }
56150         }
56151         function isValidSpreadType(type) {
56152             if (type.flags & 63176704 /* Instantiable */) {
56153                 var constraint = getBaseConstraintOfType(type);
56154                 if (constraint !== undefined) {
56155                     return isValidSpreadType(constraint);
56156                 }
56157             }
56158             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56159                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56160                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56161         }
56162         function checkJsxSelfClosingElementDeferred(node) {
56163             checkJsxOpeningLikeElementOrOpeningFragment(node);
56164             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56165         }
56166         function checkJsxSelfClosingElement(node, _checkMode) {
56167             checkNodeDeferred(node);
56168             return getJsxElementTypeAt(node) || anyType;
56169         }
56170         function checkJsxElementDeferred(node) {
56171             // Check attributes
56172             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56173             // Perform resolution on the closing tag so that rename/go to definition/etc work
56174             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56175                 getIntrinsicTagSymbol(node.closingElement);
56176             }
56177             else {
56178                 checkExpression(node.closingElement.tagName);
56179             }
56180             checkJsxChildren(node);
56181         }
56182         function checkJsxElement(node, _checkMode) {
56183             checkNodeDeferred(node);
56184             return getJsxElementTypeAt(node) || anyType;
56185         }
56186         function checkJsxFragment(node) {
56187             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56188             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56189                 error(node, compilerOptions.jsxFactory
56190                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56191                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56192             }
56193             checkJsxChildren(node);
56194             return getJsxElementTypeAt(node) || anyType;
56195         }
56196         /**
56197          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56198          */
56199         function isUnhyphenatedJsxName(name) {
56200             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56201             return !ts.stringContains(name, "-");
56202         }
56203         /**
56204          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56205          */
56206         function isJsxIntrinsicIdentifier(tagName) {
56207             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56208         }
56209         function checkJsxAttribute(node, checkMode) {
56210             return node.initializer
56211                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56212                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56213         }
56214         /**
56215          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56216          *
56217          * @param openingLikeElement a JSX opening-like element
56218          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56219          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56220          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56221          * which also calls getSpreadType.
56222          */
56223         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56224             var attributes = openingLikeElement.attributes;
56225             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56226             var attributesTable = ts.createSymbolTable();
56227             var spread = emptyJsxObjectType;
56228             var hasSpreadAnyType = false;
56229             var typeToIntersect;
56230             var explicitlySpecifyChildrenAttribute = false;
56231             var objectFlags = 4096 /* JsxAttributes */;
56232             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56233             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56234                 var attributeDecl = _a[_i];
56235                 var member = attributeDecl.symbol;
56236                 if (ts.isJsxAttribute(attributeDecl)) {
56237                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56238                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56239                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56240                     attributeSymbol.declarations = member.declarations;
56241                     attributeSymbol.parent = member.parent;
56242                     if (member.valueDeclaration) {
56243                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56244                     }
56245                     attributeSymbol.type = exprType;
56246                     attributeSymbol.target = member;
56247                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56248                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56249                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56250                         explicitlySpecifyChildrenAttribute = true;
56251                     }
56252                 }
56253                 else {
56254                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56255                     if (attributesTable.size > 0) {
56256                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56257                         attributesTable = ts.createSymbolTable();
56258                     }
56259                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56260                     if (isTypeAny(exprType)) {
56261                         hasSpreadAnyType = true;
56262                     }
56263                     if (isValidSpreadType(exprType)) {
56264                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56265                         if (allAttributesTable) {
56266                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56267                         }
56268                     }
56269                     else {
56270                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56271                     }
56272                 }
56273             }
56274             if (!hasSpreadAnyType) {
56275                 if (attributesTable.size > 0) {
56276                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56277                 }
56278             }
56279             // Handle children attribute
56280             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56281             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56282             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56283                 var childrenTypes = checkJsxChildren(parent, checkMode);
56284                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56285                     // Error if there is a attribute named "children" explicitly specified and children element.
56286                     // This is because children element will overwrite the value from attributes.
56287                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56288                     if (explicitlySpecifyChildrenAttribute) {
56289                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56290                     }
56291                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56292                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56293                     // 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
56294                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56295                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56296                         childrenTypes[0] :
56297                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56298                     // Fake up a property declaration for the children
56299                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56300                     childrenPropSymbol.valueDeclaration.parent = attributes;
56301                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56302                     var childPropMap = ts.createSymbolTable();
56303                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56304                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56305                 }
56306             }
56307             if (hasSpreadAnyType) {
56308                 return anyType;
56309             }
56310             if (typeToIntersect && spread !== emptyJsxObjectType) {
56311                 return getIntersectionType([typeToIntersect, spread]);
56312             }
56313             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56314             /**
56315              * Create anonymous type from given attributes symbol table.
56316              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56317              * @param attributesTable a symbol table of attributes property
56318              */
56319             function createJsxAttributesType() {
56320                 objectFlags |= freshObjectLiteralFlag;
56321                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56322                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56323                 return result;
56324             }
56325         }
56326         function checkJsxChildren(node, checkMode) {
56327             var childrenTypes = [];
56328             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56329                 var child = _a[_i];
56330                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56331                 // because then type of children property will have constituent of string type.
56332                 if (child.kind === 11 /* JsxText */) {
56333                     if (!child.containsOnlyTriviaWhiteSpaces) {
56334                         childrenTypes.push(stringType);
56335                     }
56336                 }
56337                 else {
56338                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56339                 }
56340             }
56341             return childrenTypes;
56342         }
56343         function checkSpreadPropOverrides(type, props, spread) {
56344             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56345                 var right = _a[_i];
56346                 var left = props.get(right.escapedName);
56347                 var rightType = getTypeOfSymbol(right);
56348                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56349                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56350                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56351                 }
56352             }
56353         }
56354         /**
56355          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56356          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56357          * @param node a JSXAttributes to be resolved of its type
56358          */
56359         function checkJsxAttributes(node, checkMode) {
56360             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56361         }
56362         function getJsxType(name, location) {
56363             var namespace = getJsxNamespaceAt(location);
56364             var exports = namespace && getExportsOfSymbol(namespace);
56365             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56366             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56367         }
56368         /**
56369          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56370          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56371          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56372          * May also return unknownSymbol if both of these lookups fail.
56373          */
56374         function getIntrinsicTagSymbol(node) {
56375             var links = getNodeLinks(node);
56376             if (!links.resolvedSymbol) {
56377                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56378                 if (intrinsicElementsType !== errorType) {
56379                     // Property case
56380                     if (!ts.isIdentifier(node.tagName))
56381                         return ts.Debug.fail();
56382                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56383                     if (intrinsicProp) {
56384                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56385                         return links.resolvedSymbol = intrinsicProp;
56386                     }
56387                     // Intrinsic string indexer case
56388                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56389                     if (indexSignatureType) {
56390                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56391                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56392                     }
56393                     // Wasn't found
56394                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56395                     return links.resolvedSymbol = unknownSymbol;
56396                 }
56397                 else {
56398                     if (noImplicitAny) {
56399                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56400                     }
56401                     return links.resolvedSymbol = unknownSymbol;
56402                 }
56403             }
56404             return links.resolvedSymbol;
56405         }
56406         function getJsxNamespaceAt(location) {
56407             var links = location && getNodeLinks(location);
56408             if (links && links.jsxNamespace) {
56409                 return links.jsxNamespace;
56410             }
56411             if (!links || links.jsxNamespace !== false) {
56412                 var namespaceName = getJsxNamespace(location);
56413                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56414                 if (resolvedNamespace) {
56415                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56416                     if (candidate) {
56417                         if (links) {
56418                             links.jsxNamespace = candidate;
56419                         }
56420                         return candidate;
56421                     }
56422                     if (links) {
56423                         links.jsxNamespace = false;
56424                     }
56425                 }
56426             }
56427             // JSX global fallback
56428             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56429         }
56430         /**
56431          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56432          * Get a single property from that container if existed. Report an error if there are more than one property.
56433          *
56434          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56435          *          if other string is given or the container doesn't exist, return undefined.
56436          */
56437         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56438             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56439             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56440             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56441             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56442             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56443             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56444             if (propertiesOfJsxElementAttribPropInterface) {
56445                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56446                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56447                     return "";
56448                 }
56449                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56450                 // property of the class instance type
56451                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56452                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56453                 }
56454                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56455                     // More than one property on ElementAttributesProperty is an error
56456                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56457                 }
56458             }
56459             return undefined;
56460         }
56461         function getJsxLibraryManagedAttributes(jsxNamespace) {
56462             // JSX.LibraryManagedAttributes [symbol]
56463             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56464         }
56465         /// e.g. "props" for React.d.ts,
56466         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56467         ///     non-intrinsic elements' attributes type is 'any'),
56468         /// or '' if it has 0 properties (which means every
56469         ///     non-intrinsic elements' attributes type is the element instance type)
56470         function getJsxElementPropertiesName(jsxNamespace) {
56471             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56472         }
56473         function getJsxElementChildrenPropertyName(jsxNamespace) {
56474             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56475         }
56476         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56477             if (elementType.flags & 4 /* String */) {
56478                 return [anySignature];
56479             }
56480             else if (elementType.flags & 128 /* StringLiteral */) {
56481                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56482                 if (!intrinsicType) {
56483                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56484                     return ts.emptyArray;
56485                 }
56486                 else {
56487                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56488                     return [fakeSignature];
56489                 }
56490             }
56491             var apparentElemType = getApparentType(elementType);
56492             // Resolve the signatures, preferring constructor
56493             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56494             if (signatures.length === 0) {
56495                 // No construct signatures, try call signatures
56496                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56497             }
56498             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56499                 // If each member has some combination of new/call signatures; make a union signature list for those
56500                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56501             }
56502             return signatures;
56503         }
56504         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56505             // 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
56506             // For example:
56507             //      var CustomTag: "h1" = "h1";
56508             //      <CustomTag> Hello World </CustomTag>
56509             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56510             if (intrinsicElementsType !== errorType) {
56511                 var stringLiteralTypeName = type.value;
56512                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56513                 if (intrinsicProp) {
56514                     return getTypeOfSymbol(intrinsicProp);
56515                 }
56516                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56517                 if (indexSignatureType) {
56518                     return indexSignatureType;
56519                 }
56520                 return undefined;
56521             }
56522             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56523             return anyType;
56524         }
56525         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56526             if (refKind === 1 /* Function */) {
56527                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56528                 if (sfcReturnConstraint) {
56529                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56530                 }
56531             }
56532             else if (refKind === 0 /* Component */) {
56533                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56534                 if (classConstraint) {
56535                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56536                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56537                 }
56538             }
56539             else { // Mixed
56540                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56541                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56542                 if (!sfcReturnConstraint || !classConstraint) {
56543                     return;
56544                 }
56545                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56546                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56547             }
56548             function generateInitialErrorChain() {
56549                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56550                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56551             }
56552         }
56553         /**
56554          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56555          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56556          * @param node an intrinsic JSX opening-like element
56557          */
56558         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56559             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56560             var links = getNodeLinks(node);
56561             if (!links.resolvedJsxElementAttributesType) {
56562                 var symbol = getIntrinsicTagSymbol(node);
56563                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56564                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56565                 }
56566                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56567                     return links.resolvedJsxElementAttributesType =
56568                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56569                 }
56570                 else {
56571                     return links.resolvedJsxElementAttributesType = errorType;
56572                 }
56573             }
56574             return links.resolvedJsxElementAttributesType;
56575         }
56576         function getJsxElementClassTypeAt(location) {
56577             var type = getJsxType(JsxNames.ElementClass, location);
56578             if (type === errorType)
56579                 return undefined;
56580             return type;
56581         }
56582         function getJsxElementTypeAt(location) {
56583             return getJsxType(JsxNames.Element, location);
56584         }
56585         function getJsxStatelessElementTypeAt(location) {
56586             var jsxElementType = getJsxElementTypeAt(location);
56587             if (jsxElementType) {
56588                 return getUnionType([jsxElementType, nullType]);
56589             }
56590         }
56591         /**
56592          * Returns all the properties of the Jsx.IntrinsicElements interface
56593          */
56594         function getJsxIntrinsicTagNamesAt(location) {
56595             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56596             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56597         }
56598         function checkJsxPreconditions(errorNode) {
56599             // Preconditions for using JSX
56600             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56601                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56602             }
56603             if (getJsxElementTypeAt(errorNode) === undefined) {
56604                 if (noImplicitAny) {
56605                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56606                 }
56607             }
56608         }
56609         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56610             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56611             if (isNodeOpeningLikeElement) {
56612                 checkGrammarJsxElement(node);
56613             }
56614             checkJsxPreconditions(node);
56615             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56616             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56617             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56618             var reactNamespace = getJsxNamespace(node);
56619             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56620             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56621             if (reactSym) {
56622                 // Mark local symbol as referenced here because it might not have been marked
56623                 // if jsx emit was not react as there wont be error being emitted
56624                 reactSym.isReferenced = 67108863 /* All */;
56625                 // If react symbol is alias, mark it as refereced
56626                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56627                     markAliasSymbolAsReferenced(reactSym);
56628                 }
56629             }
56630             if (isNodeOpeningLikeElement) {
56631                 var jsxOpeningLikeNode = node;
56632                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56633                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56634             }
56635         }
56636         /**
56637          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56638          * is considered known if
56639          * 1. the object type is empty and the check is for assignability, or
56640          * 2. if the object type has index signatures, or
56641          * 3. if the property is actually declared in the object type
56642          *    (this means that 'toString', for example, is not usually a known property).
56643          * 4. In a union or intersection type,
56644          *    a property is considered known if it is known in any constituent type.
56645          * @param targetType a type to search a given name in
56646          * @param name a property name to search
56647          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56648          */
56649         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56650             if (targetType.flags & 524288 /* Object */) {
56651                 var resolved = resolveStructuredTypeMembers(targetType);
56652                 if (resolved.stringIndexInfo ||
56653                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56654                     getPropertyOfObjectType(targetType, name) ||
56655                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56656                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56657                     return true;
56658                 }
56659             }
56660             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56661                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56662                     var t = _a[_i];
56663                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56664                         return true;
56665                     }
56666                 }
56667             }
56668             return false;
56669         }
56670         function isExcessPropertyCheckTarget(type) {
56671             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56672                 type.flags & 67108864 /* NonPrimitive */ ||
56673                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56674                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56675         }
56676         function checkJsxExpression(node, checkMode) {
56677             checkGrammarJsxExpression(node);
56678             if (node.expression) {
56679                 var type = checkExpression(node.expression, checkMode);
56680                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56681                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56682                 }
56683                 return type;
56684             }
56685             else {
56686                 return errorType;
56687             }
56688         }
56689         function getDeclarationNodeFlagsFromSymbol(s) {
56690             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56691         }
56692         /**
56693          * Return whether this symbol is a member of a prototype somewhere
56694          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56695          */
56696         function isPrototypeProperty(symbol) {
56697             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56698                 return true;
56699             }
56700             if (ts.isInJSFile(symbol.valueDeclaration)) {
56701                 var parent = symbol.valueDeclaration.parent;
56702                 return parent && ts.isBinaryExpression(parent) &&
56703                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56704             }
56705         }
56706         /**
56707          * Check whether the requested property access is valid.
56708          * Returns true if node is a valid property access, and false otherwise.
56709          * @param node The node to be checked.
56710          * @param isSuper True if the access is from `super.`.
56711          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56712          * @param prop The symbol for the property being accessed.
56713          */
56714         function checkPropertyAccessibility(node, isSuper, type, prop) {
56715             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56716             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56717             if (isSuper) {
56718                 // TS 1.0 spec (April 2014): 4.8.2
56719                 // - In a constructor, instance member function, instance member accessor, or
56720                 //   instance member variable initializer where this references a derived class instance,
56721                 //   a super property access is permitted and must specify a public instance member function of the base class.
56722                 // - In a static member function or static member accessor
56723                 //   where this references the constructor function object of a derived class,
56724                 //   a super property access is permitted and must specify a public static member function of the base class.
56725                 if (languageVersion < 2 /* ES2015 */) {
56726                     if (symbolHasNonMethodDeclaration(prop)) {
56727                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56728                         return false;
56729                     }
56730                 }
56731                 if (flags & 128 /* Abstract */) {
56732                     // A method cannot be accessed in a super property access if the method is abstract.
56733                     // This error could mask a private property access error. But, a member
56734                     // cannot simultaneously be private and abstract, so this will trigger an
56735                     // additional error elsewhere.
56736                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56737                     return false;
56738                 }
56739             }
56740             // Referencing abstract properties within their own constructors is not allowed
56741             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56742                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56743                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56744                     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
56745                     return false;
56746                 }
56747             }
56748             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56749                 if (!ts.getContainingClass(node)) {
56750                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56751                     return false;
56752                 }
56753                 return true;
56754             }
56755             // Public properties are otherwise accessible.
56756             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56757                 return true;
56758             }
56759             // Property is known to be private or protected at this point
56760             // Private property is accessible if the property is within the declaring class
56761             if (flags & 8 /* Private */) {
56762                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56763                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56764                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56765                     return false;
56766                 }
56767                 return true;
56768             }
56769             // Property is known to be protected at this point
56770             // All protected properties of a supertype are accessible in a super access
56771             if (isSuper) {
56772                 return true;
56773             }
56774             // Find the first enclosing class that has the declaring classes of the protected constituents
56775             // of the property as base classes
56776             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56777                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56778                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56779             });
56780             // A protected property is accessible if the property is within the declaring class or classes derived from it
56781             if (!enclosingClass) {
56782                 // allow PropertyAccessibility if context is in function with this parameter
56783                 // static member access is disallow
56784                 var thisParameter = void 0;
56785                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56786                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56787                     return false;
56788                 }
56789                 var thisType = getTypeFromTypeNode(thisParameter.type);
56790                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56791             }
56792             // No further restrictions for static properties
56793             if (flags & 32 /* Static */) {
56794                 return true;
56795             }
56796             if (type.flags & 262144 /* TypeParameter */) {
56797                 // get the original type -- represented as the type constraint of the 'this' type
56798                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56799             }
56800             if (!type || !hasBaseType(type, enclosingClass)) {
56801                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56802                 return false;
56803             }
56804             return true;
56805         }
56806         function getThisParameterFromNodeContext(node) {
56807             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56808             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56809         }
56810         function symbolHasNonMethodDeclaration(symbol) {
56811             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56812         }
56813         function checkNonNullExpression(node) {
56814             return checkNonNullType(checkExpression(node), node);
56815         }
56816         function isNullableType(type) {
56817             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
56818         }
56819         function getNonNullableTypeIfNeeded(type) {
56820             return isNullableType(type) ? getNonNullableType(type) : type;
56821         }
56822         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
56823             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56824                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
56825                 ts.Diagnostics.Object_is_possibly_undefined :
56826                 ts.Diagnostics.Object_is_possibly_null);
56827         }
56828         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
56829             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56830                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
56831                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
56832                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
56833         }
56834         function checkNonNullTypeWithReporter(type, node, reportError) {
56835             if (strictNullChecks && type.flags & 2 /* Unknown */) {
56836                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
56837                 return errorType;
56838             }
56839             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
56840             if (kind) {
56841                 reportError(node, kind);
56842                 var t = getNonNullableType(type);
56843                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
56844             }
56845             return type;
56846         }
56847         function checkNonNullType(type, node) {
56848             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
56849         }
56850         function checkNonNullNonVoidType(type, node) {
56851             var nonNullType = checkNonNullType(type, node);
56852             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
56853                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
56854             }
56855             return nonNullType;
56856         }
56857         function checkPropertyAccessExpression(node) {
56858             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
56859                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
56860         }
56861         function checkPropertyAccessChain(node) {
56862             var leftType = checkExpression(node.expression);
56863             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
56864             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
56865         }
56866         function checkQualifiedName(node) {
56867             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
56868         }
56869         function isMethodAccessForCall(node) {
56870             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
56871                 node = node.parent;
56872             }
56873             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
56874         }
56875         // Lookup the private identifier lexically.
56876         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
56877             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
56878                 var symbol = containingClass.symbol;
56879                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
56880                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
56881                 if (prop) {
56882                     return prop;
56883                 }
56884             }
56885         }
56886         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
56887             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
56888         }
56889         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
56890             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
56891             // Find a private identifier with the same description on the type.
56892             var propertyOnType;
56893             var properties = getPropertiesOfType(leftType);
56894             if (properties) {
56895                 ts.forEach(properties, function (symbol) {
56896                     var decl = symbol.valueDeclaration;
56897                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
56898                         propertyOnType = symbol;
56899                         return true;
56900                     }
56901                 });
56902             }
56903             var diagName = diagnosticName(right);
56904             if (propertyOnType) {
56905                 var typeValueDecl = propertyOnType.valueDeclaration;
56906                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
56907                 ts.Debug.assert(!!typeClass_1);
56908                 // We found a private identifier property with the same description.
56909                 // Either:
56910                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
56911                 // - It is an attempt to access the private identifier outside of the class.
56912                 if (lexicallyScopedIdentifier) {
56913                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
56914                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
56915                     ts.Debug.assert(!!lexicalClass);
56916                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
56917                         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));
56918                         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));
56919                         return true;
56920                     }
56921                 }
56922                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
56923                 return true;
56924             }
56925             return false;
56926         }
56927         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
56928             var parentSymbol = getNodeLinks(left).resolvedSymbol;
56929             var assignmentKind = ts.getAssignmentTargetKind(node);
56930             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
56931             if (ts.isPrivateIdentifier(right)) {
56932                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
56933             }
56934             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
56935             var prop;
56936             if (ts.isPrivateIdentifier(right)) {
56937                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
56938                 if (isAnyLike) {
56939                     if (lexicallyScopedSymbol) {
56940                         return apparentType;
56941                     }
56942                     if (!ts.getContainingClass(right)) {
56943                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56944                         return anyType;
56945                     }
56946                 }
56947                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
56948                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
56949                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
56950                     return errorType;
56951                 }
56952             }
56953             else {
56954                 if (isAnyLike) {
56955                     if (ts.isIdentifier(left) && parentSymbol) {
56956                         markAliasReferenced(parentSymbol, node);
56957                     }
56958                     return apparentType;
56959                 }
56960                 prop = getPropertyOfType(apparentType, right.escapedText);
56961             }
56962             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
56963                 markAliasReferenced(parentSymbol, node);
56964             }
56965             var propType;
56966             if (!prop) {
56967                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
56968                 if (!(indexInfo && indexInfo.type)) {
56969                     if (isJSLiteralType(leftType)) {
56970                         return anyType;
56971                     }
56972                     if (leftType.symbol === globalThisSymbol) {
56973                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
56974                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
56975                         }
56976                         else if (noImplicitAny) {
56977                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
56978                         }
56979                         return anyType;
56980                     }
56981                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
56982                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
56983                     }
56984                     return errorType;
56985                 }
56986                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
56987                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
56988                 }
56989                 propType = indexInfo.type;
56990             }
56991             else {
56992                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
56993                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
56994                 getNodeLinks(node).resolvedSymbol = prop;
56995                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
56996                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
56997                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
56998                     return errorType;
56999                 }
57000                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57001             }
57002             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57003         }
57004         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57005             // Only compute control flow type if this is a property access expression that isn't an
57006             // assignment target, and the referenced property was declared as a variable, property,
57007             // accessor, or optional method.
57008             var assignmentKind = ts.getAssignmentTargetKind(node);
57009             if (!ts.isAccessExpression(node) ||
57010                 assignmentKind === 1 /* Definite */ ||
57011                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57012                 return propType;
57013             }
57014             // If strict null checks and strict property initialization checks are enabled, if we have
57015             // a this.xxx property access, if the property is an instance property without an initializer,
57016             // and if we are in a constructor of the same class as the property declaration, assume that
57017             // the property is uninitialized at the top of the control flow.
57018             var assumeUninitialized = false;
57019             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57020                 var declaration = prop && prop.valueDeclaration;
57021                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57022                     var flowContainer = getControlFlowContainer(node);
57023                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57024                         assumeUninitialized = true;
57025                     }
57026                 }
57027             }
57028             else if (strictNullChecks && prop && prop.valueDeclaration &&
57029                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57030                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57031                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57032                 assumeUninitialized = true;
57033             }
57034             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57035             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57036                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57037                 // Return the declared type to reduce follow-on errors
57038                 return propType;
57039             }
57040             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57041         }
57042         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57043             var valueDeclaration = prop.valueDeclaration;
57044             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57045                 return;
57046             }
57047             var diagnosticMessage;
57048             var declarationName = ts.idText(right);
57049             if (isInPropertyInitializer(node)
57050                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57051                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57052                 && !isPropertyDeclaredInAncestorClass(prop)) {
57053                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57054             }
57055             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57056                 node.parent.kind !== 169 /* TypeReference */ &&
57057                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57058                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57059                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57060             }
57061             if (diagnosticMessage) {
57062                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57063             }
57064         }
57065         function isInPropertyInitializer(node) {
57066             return !!ts.findAncestor(node, function (node) {
57067                 switch (node.kind) {
57068                     case 159 /* PropertyDeclaration */:
57069                         return true;
57070                     case 281 /* PropertyAssignment */:
57071                     case 161 /* MethodDeclaration */:
57072                     case 163 /* GetAccessor */:
57073                     case 164 /* SetAccessor */:
57074                     case 283 /* SpreadAssignment */:
57075                     case 154 /* ComputedPropertyName */:
57076                     case 221 /* TemplateSpan */:
57077                     case 276 /* JsxExpression */:
57078                     case 273 /* JsxAttribute */:
57079                     case 274 /* JsxAttributes */:
57080                     case 275 /* JsxSpreadAttribute */:
57081                     case 268 /* JsxOpeningElement */:
57082                     case 216 /* ExpressionWithTypeArguments */:
57083                     case 279 /* HeritageClause */:
57084                         return false;
57085                     default:
57086                         return ts.isExpressionNode(node) ? false : "quit";
57087                 }
57088             });
57089         }
57090         /**
57091          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57092          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57093          */
57094         function isPropertyDeclaredInAncestorClass(prop) {
57095             if (!(prop.parent.flags & 32 /* Class */)) {
57096                 return false;
57097             }
57098             var classType = getTypeOfSymbol(prop.parent);
57099             while (true) {
57100                 classType = classType.symbol && getSuperClass(classType);
57101                 if (!classType) {
57102                     return false;
57103                 }
57104                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57105                 if (superProperty && superProperty.valueDeclaration) {
57106                     return true;
57107                 }
57108             }
57109         }
57110         function getSuperClass(classType) {
57111             var x = getBaseTypes(classType);
57112             if (x.length === 0) {
57113                 return undefined;
57114             }
57115             return getIntersectionType(x);
57116         }
57117         function reportNonexistentProperty(propNode, containingType) {
57118             var errorInfo;
57119             var relatedInfo;
57120             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57121                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57122                     var subtype = _a[_i];
57123                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57124                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57125                         break;
57126                     }
57127                 }
57128             }
57129             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57130                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57131             }
57132             else {
57133                 var promisedType = getPromisedTypeOfPromise(containingType);
57134                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57135                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57136                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57137                 }
57138                 else {
57139                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57140                     if (suggestion !== undefined) {
57141                         var suggestedName = ts.symbolName(suggestion);
57142                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57143                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57144                     }
57145                     else {
57146                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57147                     }
57148                 }
57149             }
57150             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57151             if (relatedInfo) {
57152                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57153             }
57154             diagnostics.add(resultDiagnostic);
57155         }
57156         function typeHasStaticProperty(propName, containingType) {
57157             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57158             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57159         }
57160         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57161             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57162         }
57163         function getSuggestionForNonexistentProperty(name, containingType) {
57164             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57165             return suggestion && ts.symbolName(suggestion);
57166         }
57167         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57168             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57169             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57170                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57171                 var symbol = getSymbol(symbols, name, meaning);
57172                 // 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
57173                 // So the table *contains* `x` but `x` isn't actually in scope.
57174                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57175                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57176             });
57177             return result;
57178         }
57179         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57180             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57181             return symbolResult && ts.symbolName(symbolResult);
57182         }
57183         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57184             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57185         }
57186         function getSuggestionForNonexistentExport(name, targetModule) {
57187             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57188             return suggestion && ts.symbolName(suggestion);
57189         }
57190         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57191             // check if object type has setter or getter
57192             function hasProp(name) {
57193                 var prop = getPropertyOfObjectType(objectType, name);
57194                 if (prop) {
57195                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57196                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57197                 }
57198                 return false;
57199             }
57200             ;
57201             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57202             if (!hasProp(suggestedMethod)) {
57203                 return undefined;
57204             }
57205             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57206             if (suggestion === undefined) {
57207                 suggestion = suggestedMethod;
57208             }
57209             else {
57210                 suggestion += "." + suggestedMethod;
57211             }
57212             return suggestion;
57213         }
57214         /**
57215          * 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.
57216          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57217          *
57218          * If there is a candidate that's the same except for case, return that.
57219          * If there is a candidate that's within one edit of the name, return that.
57220          * Otherwise, return the candidate with the smallest Levenshtein distance,
57221          *    except for candidates:
57222          *      * With no name
57223          *      * Whose meaning doesn't match the `meaning` parameter.
57224          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57225          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57226          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57227          *         and 1 insertion/deletion at 3 characters)
57228          */
57229         function getSpellingSuggestionForName(name, symbols, meaning) {
57230             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57231             function getCandidateName(candidate) {
57232                 var candidateName = ts.symbolName(candidate);
57233                 if (ts.startsWith(candidateName, "\"")) {
57234                     return undefined;
57235                 }
57236                 if (candidate.flags & meaning) {
57237                     return candidateName;
57238                 }
57239                 if (candidate.flags & 2097152 /* Alias */) {
57240                     var alias = tryResolveAlias(candidate);
57241                     if (alias && alias.flags & meaning) {
57242                         return candidateName;
57243                     }
57244                 }
57245                 return undefined;
57246             }
57247         }
57248         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57249             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57250             if (!valueDeclaration) {
57251                 return;
57252             }
57253             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57254             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57255             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57256                 return;
57257             }
57258             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57259                 return;
57260             }
57261             if (isThisAccess) {
57262                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57263                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57264                 if (containingMethod && containingMethod.symbol === prop) {
57265                     return;
57266                 }
57267             }
57268             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57269         }
57270         function isValidPropertyAccess(node, propertyName) {
57271             switch (node.kind) {
57272                 case 194 /* PropertyAccessExpression */:
57273                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57274                 case 153 /* QualifiedName */:
57275                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57276                 case 188 /* ImportType */:
57277                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57278             }
57279         }
57280         function isValidPropertyAccessForCompletions(node, type, property) {
57281             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57282             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57283         }
57284         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57285             if (type === errorType || isTypeAny(type)) {
57286                 return true;
57287             }
57288             var prop = getPropertyOfType(type, propertyName);
57289             if (prop) {
57290                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57291                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57292                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57293                 }
57294                 return checkPropertyAccessibility(node, isSuper, type, prop);
57295             }
57296             // In js files properties of unions are allowed in completion
57297             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57298         }
57299         /**
57300          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57301          */
57302         function getForInVariableSymbol(node) {
57303             var initializer = node.initializer;
57304             if (initializer.kind === 243 /* VariableDeclarationList */) {
57305                 var variable = initializer.declarations[0];
57306                 if (variable && !ts.isBindingPattern(variable.name)) {
57307                     return getSymbolOfNode(variable);
57308                 }
57309             }
57310             else if (initializer.kind === 75 /* Identifier */) {
57311                 return getResolvedSymbol(initializer);
57312             }
57313             return undefined;
57314         }
57315         /**
57316          * Return true if the given type is considered to have numeric property names.
57317          */
57318         function hasNumericPropertyNames(type) {
57319             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57320         }
57321         /**
57322          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57323          * that references a for-in variable for an object with numeric property names.
57324          */
57325         function isForInVariableForNumericPropertyNames(expr) {
57326             var e = ts.skipParentheses(expr);
57327             if (e.kind === 75 /* Identifier */) {
57328                 var symbol = getResolvedSymbol(e);
57329                 if (symbol.flags & 3 /* Variable */) {
57330                     var child = expr;
57331                     var node = expr.parent;
57332                     while (node) {
57333                         if (node.kind === 231 /* ForInStatement */ &&
57334                             child === node.statement &&
57335                             getForInVariableSymbol(node) === symbol &&
57336                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57337                             return true;
57338                         }
57339                         child = node;
57340                         node = node.parent;
57341                     }
57342                 }
57343             }
57344             return false;
57345         }
57346         function checkIndexedAccess(node) {
57347             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57348                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57349         }
57350         function checkElementAccessChain(node) {
57351             var exprType = checkExpression(node.expression);
57352             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57353             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57354         }
57355         function checkElementAccessExpression(node, exprType) {
57356             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57357             var indexExpression = node.argumentExpression;
57358             var indexType = checkExpression(indexExpression);
57359             if (objectType === errorType || objectType === silentNeverType) {
57360                 return objectType;
57361             }
57362             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57363                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57364                 return errorType;
57365             }
57366             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57367             var accessFlags = ts.isAssignmentTarget(node) ?
57368                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57369                 0 /* None */;
57370             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57371             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57372         }
57373         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57374             if (expressionType === errorType) {
57375                 // There is already an error, so no need to report one.
57376                 return false;
57377             }
57378             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57379                 return false;
57380             }
57381             // Make sure the property type is the primitive symbol type
57382             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57383                 if (reportError) {
57384                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57385                 }
57386                 return false;
57387             }
57388             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57389             // global Symbol object
57390             var leftHandSide = expression.expression;
57391             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57392             if (!leftHandSideSymbol) {
57393                 return false;
57394             }
57395             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57396             if (!globalESSymbol) {
57397                 // Already errored when we tried to look up the symbol
57398                 return false;
57399             }
57400             if (leftHandSideSymbol !== globalESSymbol) {
57401                 if (reportError) {
57402                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57403                 }
57404                 return false;
57405             }
57406             return true;
57407         }
57408         function callLikeExpressionMayHaveTypeArguments(node) {
57409             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57410         }
57411         function resolveUntypedCall(node) {
57412             if (callLikeExpressionMayHaveTypeArguments(node)) {
57413                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57414                 // This gets us diagnostics for the type arguments and marks them as referenced.
57415                 ts.forEach(node.typeArguments, checkSourceElement);
57416             }
57417             if (node.kind === 198 /* TaggedTemplateExpression */) {
57418                 checkExpression(node.template);
57419             }
57420             else if (ts.isJsxOpeningLikeElement(node)) {
57421                 checkExpression(node.attributes);
57422             }
57423             else if (node.kind !== 157 /* Decorator */) {
57424                 ts.forEach(node.arguments, function (argument) {
57425                     checkExpression(argument);
57426                 });
57427             }
57428             return anySignature;
57429         }
57430         function resolveErrorCall(node) {
57431             resolveUntypedCall(node);
57432             return unknownSignature;
57433         }
57434         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57435         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57436         // A nit here is that we reorder only signatures that belong to the same symbol,
57437         // so order how inherited signatures are processed is still preserved.
57438         // interface A { (x: string): void }
57439         // interface B extends A { (x: 'foo'): string }
57440         // const b: B;
57441         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57442         function reorderCandidates(signatures, result, callChainFlags) {
57443             var lastParent;
57444             var lastSymbol;
57445             var cutoffIndex = 0;
57446             var index;
57447             var specializedIndex = -1;
57448             var spliceIndex;
57449             ts.Debug.assert(!result.length);
57450             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57451                 var signature = signatures_7[_i];
57452                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57453                 var parent = signature.declaration && signature.declaration.parent;
57454                 if (!lastSymbol || symbol === lastSymbol) {
57455                     if (lastParent && parent === lastParent) {
57456                         index = index + 1;
57457                     }
57458                     else {
57459                         lastParent = parent;
57460                         index = cutoffIndex;
57461                     }
57462                 }
57463                 else {
57464                     // current declaration belongs to a different symbol
57465                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57466                     index = cutoffIndex = result.length;
57467                     lastParent = parent;
57468                 }
57469                 lastSymbol = symbol;
57470                 // specialized signatures always need to be placed before non-specialized signatures regardless
57471                 // of the cutoff position; see GH#1133
57472                 if (signatureHasLiteralTypes(signature)) {
57473                     specializedIndex++;
57474                     spliceIndex = specializedIndex;
57475                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57476                     // in order to prevent non-specialized signatures from being added before a specialized
57477                     // signature.
57478                     cutoffIndex++;
57479                 }
57480                 else {
57481                     spliceIndex = index;
57482                 }
57483                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57484             }
57485         }
57486         function isSpreadArgument(arg) {
57487             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57488         }
57489         function getSpreadArgumentIndex(args) {
57490             return ts.findIndex(args, isSpreadArgument);
57491         }
57492         function acceptsVoid(t) {
57493             return !!(t.flags & 16384 /* Void */);
57494         }
57495         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57496             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57497             var argCount;
57498             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57499             var effectiveParameterCount = getParameterCount(signature);
57500             var effectiveMinimumArguments = getMinArgumentCount(signature);
57501             if (node.kind === 198 /* TaggedTemplateExpression */) {
57502                 argCount = args.length;
57503                 if (node.template.kind === 211 /* TemplateExpression */) {
57504                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57505                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57506                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57507                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57508                 }
57509                 else {
57510                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57511                     // then this might actually turn out to be a TemplateHead in the future;
57512                     // so we consider the call to be incomplete.
57513                     var templateLiteral = node.template;
57514                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57515                     callIsIncomplete = !!templateLiteral.isUnterminated;
57516                 }
57517             }
57518             else if (node.kind === 157 /* Decorator */) {
57519                 argCount = getDecoratorArgumentCount(node, signature);
57520             }
57521             else if (ts.isJsxOpeningLikeElement(node)) {
57522                 callIsIncomplete = node.attributes.end === node.end;
57523                 if (callIsIncomplete) {
57524                     return true;
57525                 }
57526                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57527                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57528                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57529             }
57530             else {
57531                 if (!node.arguments) {
57532                     // This only happens when we have something of the form: 'new C'
57533                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57534                     return getMinArgumentCount(signature) === 0;
57535                 }
57536                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57537                 // If we are missing the close parenthesis, the call is incomplete.
57538                 callIsIncomplete = node.arguments.end === node.end;
57539                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57540                 var spreadArgIndex = getSpreadArgumentIndex(args);
57541                 if (spreadArgIndex >= 0) {
57542                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57543                 }
57544             }
57545             // Too many arguments implies incorrect arity.
57546             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57547                 return false;
57548             }
57549             // If the call is incomplete, we should skip the lower bound check.
57550             // JSX signatures can have extra parameters provided by the library which we don't check
57551             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57552                 return true;
57553             }
57554             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57555                 var type = getTypeAtPosition(signature, i);
57556                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57557                     return false;
57558                 }
57559             }
57560             return true;
57561         }
57562         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57563             // If the user supplied type arguments, but the number of type arguments does not match
57564             // the declared number of type parameters, the call has an incorrect arity.
57565             var numTypeParameters = ts.length(signature.typeParameters);
57566             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57567             return !ts.some(typeArguments) ||
57568                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57569         }
57570         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57571         function getSingleCallSignature(type) {
57572             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57573         }
57574         function getSingleCallOrConstructSignature(type) {
57575             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57576                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57577         }
57578         function getSingleSignature(type, kind, allowMembers) {
57579             if (type.flags & 524288 /* Object */) {
57580                 var resolved = resolveStructuredTypeMembers(type);
57581                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57582                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57583                         return resolved.callSignatures[0];
57584                     }
57585                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57586                         return resolved.constructSignatures[0];
57587                     }
57588                 }
57589             }
57590             return undefined;
57591         }
57592         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57593         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57594             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57595             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57596             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57597             // for T but leave it possible to later infer '[any]' back to A.
57598             var restType = getEffectiveRestType(contextualSignature);
57599             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57600             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57601             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57602                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57603                 inferTypes(context.inferences, source, target);
57604             });
57605             if (!inferenceContext) {
57606                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57607                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57608                 });
57609             }
57610             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57611         }
57612         function inferJsxTypeArguments(node, signature, checkMode, context) {
57613             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57614             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57615             inferTypes(context.inferences, checkAttrType, paramType);
57616             return getInferredTypes(context);
57617         }
57618         function inferTypeArguments(node, signature, args, checkMode, context) {
57619             if (ts.isJsxOpeningLikeElement(node)) {
57620                 return inferJsxTypeArguments(node, signature, checkMode, context);
57621             }
57622             // If a contextual type is available, infer from that type to the return type of the call expression. For
57623             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57624             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57625             // return type of 'wrap'.
57626             if (node.kind !== 157 /* Decorator */) {
57627                 var contextualType = getContextualType(node);
57628                 if (contextualType) {
57629                     // We clone the inference context to avoid disturbing a resolution in progress for an
57630                     // outer call expression. Effectively we just want a snapshot of whatever has been
57631                     // inferred for any outer call expression so far.
57632                     var outerContext = getInferenceContext(node);
57633                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57634                     var instantiatedType = instantiateType(contextualType, outerMapper);
57635                     // If the contextual type is a generic function type with a single call signature, we
57636                     // instantiate the type with its own type parameters and type arguments. This ensures that
57637                     // the type parameters are not erased to type any during type inference such that they can
57638                     // be inferred as actual types from the contextual type. For example:
57639                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57640                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57641                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57642                     var contextualSignature = getSingleCallSignature(instantiatedType);
57643                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57644                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57645                         instantiatedType;
57646                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57647                     // Inferences made from return types have lower priority than all other inferences.
57648                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57649                     // Create a type mapper for instantiating generic contextual types using the inferences made
57650                     // from the return type. We need a separate inference pass here because (a) instantiation of
57651                     // the source type uses the outer context's return mapper (which excludes inferences made from
57652                     // outer arguments), and (b) we don't want any further inferences going into this context.
57653                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57654                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57655                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57656                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57657                 }
57658             }
57659             var thisType = getThisTypeOfSignature(signature);
57660             if (thisType) {
57661                 var thisArgumentNode = getThisArgumentOfCall(node);
57662                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57663                 inferTypes(context.inferences, thisArgumentType, thisType);
57664             }
57665             var restType = getNonArrayRestType(signature);
57666             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57667             for (var i = 0; i < argCount; i++) {
57668                 var arg = args[i];
57669                 if (arg.kind !== 215 /* OmittedExpression */) {
57670                     var paramType = getTypeAtPosition(signature, i);
57671                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57672                     inferTypes(context.inferences, argType, paramType);
57673                 }
57674             }
57675             if (restType) {
57676                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57677                 inferTypes(context.inferences, spreadType, restType);
57678             }
57679             return getInferredTypes(context);
57680         }
57681         function getArrayifiedType(type) {
57682             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57683                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57684                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57685                         createArrayType(getIndexedAccessType(type, numberType));
57686         }
57687         function getSpreadArgumentType(args, index, argCount, restType, context) {
57688             if (index >= argCount - 1) {
57689                 var arg = args[argCount - 1];
57690                 if (isSpreadArgument(arg)) {
57691                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57692                     // and the argument are ...x forms.
57693                     return arg.kind === 220 /* SyntheticExpression */ ?
57694                         createArrayType(arg.type) :
57695                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57696                 }
57697             }
57698             var types = [];
57699             var spreadIndex = -1;
57700             for (var i = index; i < argCount; i++) {
57701                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57702                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57703                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57704                     spreadIndex = i - index;
57705                 }
57706                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57707                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57708             }
57709             return spreadIndex < 0 ?
57710                 createTupleType(types) :
57711                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57712         }
57713         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57714             var isJavascript = ts.isInJSFile(signature.declaration);
57715             var typeParameters = signature.typeParameters;
57716             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57717             var mapper;
57718             for (var i = 0; i < typeArgumentNodes.length; i++) {
57719                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57720                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57721                 if (constraint) {
57722                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57723                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57724                     if (!mapper) {
57725                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57726                     }
57727                     var typeArgument = typeArgumentTypes[i];
57728                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57729                         return undefined;
57730                     }
57731                 }
57732             }
57733             return typeArgumentTypes;
57734         }
57735         function getJsxReferenceKind(node) {
57736             if (isJsxIntrinsicIdentifier(node.tagName)) {
57737                 return 2 /* Mixed */;
57738             }
57739             var tagType = getApparentType(checkExpression(node.tagName));
57740             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57741                 return 0 /* Component */;
57742             }
57743             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57744                 return 1 /* Function */;
57745             }
57746             return 2 /* Mixed */;
57747         }
57748         /**
57749          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57750          * @param node a JSX opening-like element we are trying to figure its call signature
57751          * @param signature a candidate signature we are trying whether it is a call signature
57752          * @param relation a relationship to check parameter and argument type
57753          */
57754         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57755             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57756             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57757             // can be specified by users through attributes property.
57758             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57759             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57760             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57761             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57762             function checkTagNameDoesNotExpectTooManyArguments() {
57763                 var _a;
57764                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57765                 if (!tagType) {
57766                     return true;
57767                 }
57768                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57769                 if (!ts.length(tagCallSignatures)) {
57770                     return true;
57771                 }
57772                 var factory = getJsxFactoryEntity(node);
57773                 if (!factory) {
57774                     return true;
57775                 }
57776                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57777                 if (!factorySymbol) {
57778                     return true;
57779                 }
57780                 var factoryType = getTypeOfSymbol(factorySymbol);
57781                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57782                 if (!ts.length(callSignatures)) {
57783                     return true;
57784                 }
57785                 var hasFirstParamSignatures = false;
57786                 var maxParamCount = 0;
57787                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57788                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57789                     var sig = callSignatures_1[_i];
57790                     var firstparam = getTypeAtPosition(sig, 0);
57791                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57792                     if (!ts.length(signaturesOfParam))
57793                         continue;
57794                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57795                         var paramSig = signaturesOfParam_1[_b];
57796                         hasFirstParamSignatures = true;
57797                         if (hasEffectiveRestParameter(paramSig)) {
57798                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57799                         }
57800                         var paramCount = getParameterCount(paramSig);
57801                         if (paramCount > maxParamCount) {
57802                             maxParamCount = paramCount;
57803                         }
57804                     }
57805                 }
57806                 if (!hasFirstParamSignatures) {
57807                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57808                     // to guard against generic factories which won't have signatures directly, do not error
57809                     return true;
57810                 }
57811                 var absoluteMinArgCount = Infinity;
57812                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57813                     var tagSig = tagCallSignatures_1[_c];
57814                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57815                     if (tagRequiredArgCount < absoluteMinArgCount) {
57816                         absoluteMinArgCount = tagRequiredArgCount;
57817                     }
57818                 }
57819                 if (absoluteMinArgCount <= maxParamCount) {
57820                     return true; // some signature accepts the number of arguments the function component provides
57821                 }
57822                 if (reportErrors) {
57823                     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);
57824                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
57825                     if (tagNameDeclaration) {
57826                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
57827                     }
57828                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
57829                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57830                     }
57831                     if (!errorOutputContainer.skipLogging) {
57832                         diagnostics.add(diag);
57833                     }
57834                 }
57835                 return false;
57836             }
57837         }
57838         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
57839             var errorOutputContainer = { errors: undefined, skipLogging: true };
57840             if (ts.isJsxOpeningLikeElement(node)) {
57841                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
57842                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
57843                     return errorOutputContainer.errors || ts.emptyArray;
57844                 }
57845                 return undefined;
57846             }
57847             var thisType = getThisTypeOfSignature(signature);
57848             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
57849                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
57850                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
57851                 // If the expression is a new expression, then the check is skipped.
57852                 var thisArgumentNode = getThisArgumentOfCall(node);
57853                 var thisArgumentType = void 0;
57854                 if (thisArgumentNode) {
57855                     thisArgumentType = checkExpression(thisArgumentNode);
57856                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
57857                         thisArgumentType = getNonNullableType(thisArgumentType);
57858                     }
57859                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
57860                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
57861                     }
57862                 }
57863                 else {
57864                     thisArgumentType = voidType;
57865                 }
57866                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
57867                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
57868                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
57869                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
57870                     return errorOutputContainer.errors || ts.emptyArray;
57871                 }
57872             }
57873             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
57874             var restType = getNonArrayRestType(signature);
57875             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57876             for (var i = 0; i < argCount; i++) {
57877                 var arg = args[i];
57878                 if (arg.kind !== 215 /* OmittedExpression */) {
57879                     var paramType = getTypeAtPosition(signature, i);
57880                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
57881                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
57882                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
57883                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
57884                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
57885                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
57886                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
57887                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
57888                         return errorOutputContainer.errors || ts.emptyArray;
57889                     }
57890                 }
57891             }
57892             if (restType) {
57893                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
57894                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
57895                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
57896                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
57897                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
57898                     return errorOutputContainer.errors || ts.emptyArray;
57899                 }
57900             }
57901             return undefined;
57902             function maybeAddMissingAwaitInfo(errorNode, source, target) {
57903                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
57904                     // Bail if target is Promise-like---something else is wrong
57905                     if (getAwaitedTypeOfPromise(target)) {
57906                         return;
57907                     }
57908                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
57909                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
57910                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
57911                     }
57912                 }
57913             }
57914         }
57915         /**
57916          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
57917          */
57918         function getThisArgumentOfCall(node) {
57919             if (node.kind === 196 /* CallExpression */) {
57920                 var callee = ts.skipOuterExpressions(node.expression);
57921                 if (ts.isAccessExpression(callee)) {
57922                     return callee.expression;
57923                 }
57924             }
57925         }
57926         function createSyntheticExpression(parent, type, isSpread) {
57927             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
57928             result.parent = parent;
57929             result.type = type;
57930             result.isSpread = isSpread || false;
57931             return result;
57932         }
57933         /**
57934          * Returns the effective arguments for an expression that works like a function invocation.
57935          */
57936         function getEffectiveCallArguments(node) {
57937             if (node.kind === 198 /* TaggedTemplateExpression */) {
57938                 var template = node.template;
57939                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
57940                 if (template.kind === 211 /* TemplateExpression */) {
57941                     ts.forEach(template.templateSpans, function (span) {
57942                         args_3.push(span.expression);
57943                     });
57944                 }
57945                 return args_3;
57946             }
57947             if (node.kind === 157 /* Decorator */) {
57948                 return getEffectiveDecoratorArguments(node);
57949             }
57950             if (ts.isJsxOpeningLikeElement(node)) {
57951                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
57952             }
57953             var args = node.arguments || ts.emptyArray;
57954             var length = args.length;
57955             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
57956                 // We have a spread argument in the last position and no other spread arguments. If the type
57957                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
57958                 // call checkExpressionCached because spread expressions never have a contextual type.
57959                 var spreadArgument_1 = args[length - 1];
57960                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
57961                 if (isTupleType(type)) {
57962                     var typeArguments = getTypeArguments(type);
57963                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
57964                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
57965                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
57966                 }
57967             }
57968             return args;
57969         }
57970         /**
57971          * Returns the synthetic argument list for a decorator invocation.
57972          */
57973         function getEffectiveDecoratorArguments(node) {
57974             var parent = node.parent;
57975             var expr = node.expression;
57976             switch (parent.kind) {
57977                 case 245 /* ClassDeclaration */:
57978                 case 214 /* ClassExpression */:
57979                     // For a class decorator, the `target` is the type of the class (e.g. the
57980                     // "static" or "constructor" side of the class).
57981                     return [
57982                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
57983                     ];
57984                 case 156 /* Parameter */:
57985                     // A parameter declaration decorator will have three arguments (see
57986                     // `ParameterDecorator` in core.d.ts).
57987                     var func = parent.parent;
57988                     return [
57989                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
57990                         createSyntheticExpression(expr, anyType),
57991                         createSyntheticExpression(expr, numberType)
57992                     ];
57993                 case 159 /* PropertyDeclaration */:
57994                 case 161 /* MethodDeclaration */:
57995                 case 163 /* GetAccessor */:
57996                 case 164 /* SetAccessor */:
57997                     // A method or accessor declaration decorator will have two or three arguments (see
57998                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
57999                     // for ES3, we will only pass two arguments.
58000                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58001                     return [
58002                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58003                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58004                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58005                     ];
58006             }
58007             return ts.Debug.fail();
58008         }
58009         /**
58010          * Returns the argument count for a decorator node that works like a function invocation.
58011          */
58012         function getDecoratorArgumentCount(node, signature) {
58013             switch (node.parent.kind) {
58014                 case 245 /* ClassDeclaration */:
58015                 case 214 /* ClassExpression */:
58016                     return 1;
58017                 case 159 /* PropertyDeclaration */:
58018                     return 2;
58019                 case 161 /* MethodDeclaration */:
58020                 case 163 /* GetAccessor */:
58021                 case 164 /* SetAccessor */:
58022                     // For ES3 or decorators with only two parameters we supply only two arguments
58023                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58024                 case 156 /* Parameter */:
58025                     return 3;
58026                 default:
58027                     return ts.Debug.fail();
58028             }
58029         }
58030         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58031             var start;
58032             var length;
58033             var sourceFile = ts.getSourceFileOfNode(node);
58034             if (ts.isPropertyAccessExpression(node.expression)) {
58035                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58036                 start = nameSpan.start;
58037                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58038             }
58039             else {
58040                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58041                 start = expressionSpan.start;
58042                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58043             }
58044             return { start: start, length: length, sourceFile: sourceFile };
58045         }
58046         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58047             if (ts.isCallExpression(node)) {
58048                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58049                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58050             }
58051             else {
58052                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58053             }
58054         }
58055         function getArgumentArityError(node, signatures, args) {
58056             var min = Number.POSITIVE_INFINITY;
58057             var max = Number.NEGATIVE_INFINITY;
58058             var belowArgCount = Number.NEGATIVE_INFINITY;
58059             var aboveArgCount = Number.POSITIVE_INFINITY;
58060             var argCount = args.length;
58061             var closestSignature;
58062             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58063                 var sig = signatures_8[_i];
58064                 var minCount = getMinArgumentCount(sig);
58065                 var maxCount = getParameterCount(sig);
58066                 if (minCount < argCount && minCount > belowArgCount)
58067                     belowArgCount = minCount;
58068                 if (argCount < maxCount && maxCount < aboveArgCount)
58069                     aboveArgCount = maxCount;
58070                 if (minCount < min) {
58071                     min = minCount;
58072                     closestSignature = sig;
58073                 }
58074                 max = Math.max(max, maxCount);
58075             }
58076             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58077             var paramRange = hasRestParameter ? min :
58078                 min < max ? min + "-" + max :
58079                     min;
58080             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58081             if (argCount <= max && hasSpreadArgument) {
58082                 argCount--;
58083             }
58084             var spanArray;
58085             var related;
58086             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58087                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58088                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58089             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58090                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58091                 if (paramDecl) {
58092                     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);
58093                 }
58094             }
58095             if (min < argCount && argCount < max) {
58096                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58097             }
58098             if (!hasSpreadArgument && argCount < min) {
58099                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58100                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58101             }
58102             if (hasRestParameter || hasSpreadArgument) {
58103                 spanArray = ts.createNodeArray(args);
58104                 if (hasSpreadArgument && argCount) {
58105                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58106                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58107                 }
58108             }
58109             else {
58110                 spanArray = ts.createNodeArray(args.slice(max));
58111             }
58112             spanArray.pos = ts.first(spanArray).pos;
58113             spanArray.end = ts.last(spanArray).end;
58114             if (spanArray.end === spanArray.pos) {
58115                 spanArray.end++;
58116             }
58117             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58118             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58119         }
58120         function getTypeArgumentArityError(node, signatures, typeArguments) {
58121             var argCount = typeArguments.length;
58122             // No overloads exist
58123             if (signatures.length === 1) {
58124                 var sig = signatures[0];
58125                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58126                 var max = ts.length(sig.typeParameters);
58127                 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);
58128             }
58129             // Overloads exist
58130             var belowArgCount = -Infinity;
58131             var aboveArgCount = Infinity;
58132             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58133                 var sig = signatures_9[_i];
58134                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58135                 var max = ts.length(sig.typeParameters);
58136                 if (min_2 > argCount) {
58137                     aboveArgCount = Math.min(aboveArgCount, min_2);
58138                 }
58139                 else if (max < argCount) {
58140                     belowArgCount = Math.max(belowArgCount, max);
58141                 }
58142             }
58143             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58144                 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);
58145             }
58146             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58147         }
58148         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58149             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58150             var isDecorator = node.kind === 157 /* Decorator */;
58151             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58152             var reportErrors = !candidatesOutArray;
58153             var typeArguments;
58154             if (!isDecorator) {
58155                 typeArguments = node.typeArguments;
58156                 // We already perform checking on the type arguments on the class declaration itself.
58157                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58158                     ts.forEach(typeArguments, checkSourceElement);
58159                 }
58160             }
58161             var candidates = candidatesOutArray || [];
58162             // reorderCandidates fills up the candidates array directly
58163             reorderCandidates(signatures, candidates, callChainFlags);
58164             if (!candidates.length) {
58165                 if (reportErrors) {
58166                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58167                 }
58168                 return resolveErrorCall(node);
58169             }
58170             var args = getEffectiveCallArguments(node);
58171             // The excludeArgument array contains true for each context sensitive argument (an argument
58172             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58173             //
58174             // The idea is that we will perform type argument inference & assignability checking once
58175             // without using the susceptible parameters that are functions, and once more for those
58176             // parameters, contextually typing each as we go along.
58177             //
58178             // For a tagged template, then the first argument be 'undefined' if necessary because it
58179             // represents a TemplateStringsArray.
58180             //
58181             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58182             // decorators are applied to a declaration by the emitter, and not to an expression.
58183             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58184             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58185             // The following variables are captured and modified by calls to chooseOverload.
58186             // If overload resolution or type argument inference fails, we want to report the
58187             // best error possible. The best error is one which says that an argument was not
58188             // assignable to a parameter. This implies that everything else about the overload
58189             // was fine. So if there is any overload that is only incorrect because of an
58190             // argument, we will report an error on that one.
58191             //
58192             //     function foo(s: string): void;
58193             //     function foo(n: number): void; // Report argument error on this overload
58194             //     function foo(): void;
58195             //     foo(true);
58196             //
58197             // If none of the overloads even made it that far, there are two possibilities.
58198             // There was a problem with type arguments for some overload, in which case
58199             // report an error on that. Or none of the overloads even had correct arity,
58200             // in which case give an arity error.
58201             //
58202             //     function foo<T extends string>(x: T): void; // Report type argument error
58203             //     function foo(): void;
58204             //     foo<number>(0);
58205             //
58206             var candidatesForArgumentError;
58207             var candidateForArgumentArityError;
58208             var candidateForTypeArgumentError;
58209             var result;
58210             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58211             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58212             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58213             // Section 4.12.1:
58214             // if the candidate list contains one or more signatures for which the type of each argument
58215             // expression is a subtype of each corresponding parameter type, the return type of the first
58216             // of those signatures becomes the return type of the function call.
58217             // Otherwise, the return type of the first signature in the candidate list becomes the return
58218             // type of the function call.
58219             //
58220             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58221             // is just important for choosing the best signature. So in the case where there is only one
58222             // signature, the subtype pass is useless. So skipping it is an optimization.
58223             if (candidates.length > 1) {
58224                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58225             }
58226             if (!result) {
58227                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58228             }
58229             if (result) {
58230                 return result;
58231             }
58232             // No signatures were applicable. Now report errors based on the last applicable signature with
58233             // no arguments excluded from assignability checks.
58234             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58235             // skip the checkApplicableSignature check.
58236             if (reportErrors) {
58237                 if (candidatesForArgumentError) {
58238                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58239                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58240                         var chain_1;
58241                         if (candidatesForArgumentError.length > 3) {
58242                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58243                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58244                         }
58245                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58246                         if (diags) {
58247                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58248                                 var d = diags_1[_i];
58249                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58250                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58251                                 }
58252                                 diagnostics.add(d);
58253                             }
58254                         }
58255                         else {
58256                             ts.Debug.fail("No error for last overload signature");
58257                         }
58258                     }
58259                     else {
58260                         var allDiagnostics = [];
58261                         var max = 0;
58262                         var min_3 = Number.MAX_VALUE;
58263                         var minIndex = 0;
58264                         var i_1 = 0;
58265                         var _loop_17 = function (c) {
58266                             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)); };
58267                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58268                             if (diags_2) {
58269                                 if (diags_2.length <= min_3) {
58270                                     min_3 = diags_2.length;
58271                                     minIndex = i_1;
58272                                 }
58273                                 max = Math.max(max, diags_2.length);
58274                                 allDiagnostics.push(diags_2);
58275                             }
58276                             else {
58277                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58278                             }
58279                             i_1++;
58280                         };
58281                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58282                             var c = candidatesForArgumentError_1[_a];
58283                             _loop_17(c);
58284                         }
58285                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58286                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58287                         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);
58288                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58289                         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; })) {
58290                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58291                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58292                         }
58293                         else {
58294                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58295                         }
58296                     }
58297                 }
58298                 else if (candidateForArgumentArityError) {
58299                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58300                 }
58301                 else if (candidateForTypeArgumentError) {
58302                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58303                 }
58304                 else {
58305                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58306                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58307                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58308                     }
58309                     else if (!isDecorator) {
58310                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58311                     }
58312                     else if (fallbackError) {
58313                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58314                     }
58315                 }
58316             }
58317             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58318             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58319                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58320                 candidatesForArgumentError = undefined;
58321                 candidateForArgumentArityError = undefined;
58322                 candidateForTypeArgumentError = undefined;
58323                 if (isSingleNonGenericCandidate) {
58324                     var candidate = candidates[0];
58325                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58326                         return undefined;
58327                     }
58328                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58329                         candidatesForArgumentError = [candidate];
58330                         return undefined;
58331                     }
58332                     return candidate;
58333                 }
58334                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58335                     var candidate = candidates[candidateIndex];
58336                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58337                         continue;
58338                     }
58339                     var checkCandidate = void 0;
58340                     var inferenceContext = void 0;
58341                     if (candidate.typeParameters) {
58342                         var typeArgumentTypes = void 0;
58343                         if (ts.some(typeArguments)) {
58344                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58345                             if (!typeArgumentTypes) {
58346                                 candidateForTypeArgumentError = candidate;
58347                                 continue;
58348                             }
58349                         }
58350                         else {
58351                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58352                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58353                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58354                         }
58355                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58356                         // If the original signature has a generic rest type, instantiation may produce a
58357                         // signature with different arity and we need to perform another arity check.
58358                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58359                             candidateForArgumentArityError = checkCandidate;
58360                             continue;
58361                         }
58362                     }
58363                     else {
58364                         checkCandidate = candidate;
58365                     }
58366                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58367                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58368                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58369                         continue;
58370                     }
58371                     if (argCheckMode) {
58372                         // If one or more context sensitive arguments were excluded, we start including
58373                         // them now (and keeping do so for any subsequent candidates) and perform a second
58374                         // round of type inference and applicability checking for this particular candidate.
58375                         argCheckMode = 0 /* Normal */;
58376                         if (inferenceContext) {
58377                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58378                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58379                             // If the original signature has a generic rest type, instantiation may produce a
58380                             // signature with different arity and we need to perform another arity check.
58381                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58382                                 candidateForArgumentArityError = checkCandidate;
58383                                 continue;
58384                             }
58385                         }
58386                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58387                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58388                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58389                             continue;
58390                         }
58391                     }
58392                     candidates[candidateIndex] = checkCandidate;
58393                     return checkCandidate;
58394                 }
58395                 return undefined;
58396             }
58397         }
58398         // No signature was applicable. We have already reported the errors for the invalid signature.
58399         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58400             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58401             checkNodeDeferred(node);
58402             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58403             // Don't do this if there is a `candidatesOutArray`,
58404             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58405             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58406                 ? pickLongestCandidateSignature(node, candidates, args)
58407                 : createUnionOfSignaturesForOverloadFailure(candidates);
58408         }
58409         function createUnionOfSignaturesForOverloadFailure(candidates) {
58410             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58411             var thisParameter;
58412             if (thisParameters.length) {
58413                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58414             }
58415             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58416             var parameters = [];
58417             var _loop_18 = function (i) {
58418                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58419                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58420                     i < s.parameters.length ? s.parameters[i] : undefined; });
58421                 ts.Debug.assert(symbols.length !== 0);
58422                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58423             };
58424             for (var i = 0; i < maxNonRestParam; i++) {
58425                 _loop_18(i);
58426             }
58427             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58428             var flags = 0 /* None */;
58429             if (restParameterSymbols.length !== 0) {
58430                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58431                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58432                 flags |= 1 /* HasRestParameter */;
58433             }
58434             if (candidates.some(signatureHasLiteralTypes)) {
58435                 flags |= 2 /* HasLiteralTypes */;
58436             }
58437             return createSignature(candidates[0].declaration, 
58438             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58439             thisParameter, parameters, 
58440             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58441             /*typePredicate*/ undefined, minArgumentCount, flags);
58442         }
58443         function getNumNonRestParameters(signature) {
58444             var numParams = signature.parameters.length;
58445             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58446         }
58447         function createCombinedSymbolFromTypes(sources, types) {
58448             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58449         }
58450         function createCombinedSymbolForOverloadFailure(sources, type) {
58451             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58452             return createSymbolWithType(ts.first(sources), type);
58453         }
58454         function pickLongestCandidateSignature(node, candidates, args) {
58455             // Pick the longest signature. This way we can get a contextual type for cases like:
58456             //     declare function f(a: { xa: number; xb: number; }, b: number);
58457             //     f({ |
58458             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58459             //     declare function f<T>(k: keyof T);
58460             //     f<Foo>("
58461             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58462             var candidate = candidates[bestIndex];
58463             var typeParameters = candidate.typeParameters;
58464             if (!typeParameters) {
58465                 return candidate;
58466             }
58467             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58468             var instantiated = typeArgumentNodes
58469                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58470                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58471             candidates[bestIndex] = instantiated;
58472             return instantiated;
58473         }
58474         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58475             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58476             while (typeArguments.length > typeParameters.length) {
58477                 typeArguments.pop();
58478             }
58479             while (typeArguments.length < typeParameters.length) {
58480                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58481             }
58482             return typeArguments;
58483         }
58484         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58485             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58486             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58487             return createSignatureInstantiation(candidate, typeArgumentTypes);
58488         }
58489         function getLongestCandidateIndex(candidates, argsCount) {
58490             var maxParamsIndex = -1;
58491             var maxParams = -1;
58492             for (var i = 0; i < candidates.length; i++) {
58493                 var candidate = candidates[i];
58494                 var paramCount = getParameterCount(candidate);
58495                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58496                     return i;
58497                 }
58498                 if (paramCount > maxParams) {
58499                     maxParams = paramCount;
58500                     maxParamsIndex = i;
58501                 }
58502             }
58503             return maxParamsIndex;
58504         }
58505         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58506             if (node.expression.kind === 102 /* SuperKeyword */) {
58507                 var superType = checkSuperExpression(node.expression);
58508                 if (isTypeAny(superType)) {
58509                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58510                         var arg = _a[_i];
58511                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58512                     }
58513                     return anySignature;
58514                 }
58515                 if (superType !== errorType) {
58516                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58517                     // with the type arguments specified in the extends clause.
58518                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58519                     if (baseTypeNode) {
58520                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58521                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58522                     }
58523                 }
58524                 return resolveUntypedCall(node);
58525             }
58526             var callChainFlags;
58527             var funcType = checkExpression(node.expression);
58528             if (ts.isCallChain(node)) {
58529                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58530                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58531                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58532                         4 /* IsInnerCallChain */;
58533                 funcType = nonOptionalType;
58534             }
58535             else {
58536                 callChainFlags = 0 /* None */;
58537             }
58538             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58539             if (funcType === silentNeverType) {
58540                 return silentNeverSignature;
58541             }
58542             var apparentType = getApparentType(funcType);
58543             if (apparentType === errorType) {
58544                 // Another error has already been reported
58545                 return resolveErrorCall(node);
58546             }
58547             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58548             // but we are not including call signatures that may have been added to the Object or
58549             // Function interface, since they have none by default. This is a bit of a leap of faith
58550             // that the user will not add any.
58551             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58552             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58553             // TS 1.0 Spec: 4.12
58554             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58555             // types are provided for the argument expressions, and the result is always of type Any.
58556             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58557                 // The unknownType indicates that an error already occurred (and was reported).  No
58558                 // need to report another error in this case.
58559                 if (funcType !== errorType && node.typeArguments) {
58560                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58561                 }
58562                 return resolveUntypedCall(node);
58563             }
58564             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58565             // TypeScript employs overload resolution in typed function calls in order to support functions
58566             // with multiple call signatures.
58567             if (!callSignatures.length) {
58568                 if (numConstructSignatures) {
58569                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58570                 }
58571                 else {
58572                     var relatedInformation = void 0;
58573                     if (node.arguments.length === 1) {
58574                         var text = ts.getSourceFileOfNode(node).text;
58575                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58576                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58577                         }
58578                     }
58579                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58580                 }
58581                 return resolveErrorCall(node);
58582             }
58583             // When a call to a generic function is an argument to an outer call to a generic function for which
58584             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58585             // its contextual type to its return type, deferring the inner call processing allows the best possible
58586             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58587             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58588             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58589             // If no type arguments are specified in the inner call and at least one call signature is generic and
58590             // returns a function type, we choose to defer processing. This narrowly permits function composition
58591             // operators to flow inferences through return types, but otherwise processes calls right away. We
58592             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58593             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58594             // from which we never make inferences).
58595             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58596                 skippedGenericFunction(node, checkMode);
58597                 return resolvingSignature;
58598             }
58599             // If the function is explicitly marked with `@class`, then it must be constructed.
58600             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58601                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58602                 return resolveErrorCall(node);
58603             }
58604             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58605         }
58606         function isGenericFunctionReturningFunction(signature) {
58607             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58608         }
58609         /**
58610          * TS 1.0 spec: 4.12
58611          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58612          * but is a subtype of the Function interface, the call is an untyped function call.
58613          */
58614         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58615             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58616             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58617                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58618         }
58619         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58620             if (node.arguments && languageVersion < 1 /* ES5 */) {
58621                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58622                 if (spreadIndex >= 0) {
58623                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58624                 }
58625             }
58626             var expressionType = checkNonNullExpression(node.expression);
58627             if (expressionType === silentNeverType) {
58628                 return silentNeverSignature;
58629             }
58630             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58631             // more construct signatures, the expression is processed in the same manner as a
58632             // function call, but using the construct signatures as the initial set of candidate
58633             // signatures for overload resolution. The result type of the function call becomes
58634             // the result type of the operation.
58635             expressionType = getApparentType(expressionType);
58636             if (expressionType === errorType) {
58637                 // Another error has already been reported
58638                 return resolveErrorCall(node);
58639             }
58640             // TS 1.0 spec: 4.11
58641             // If expressionType is of type Any, Args can be any argument
58642             // list and the result of the operation is of type Any.
58643             if (isTypeAny(expressionType)) {
58644                 if (node.typeArguments) {
58645                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58646                 }
58647                 return resolveUntypedCall(node);
58648             }
58649             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58650             // but we are not including construct signatures that may have been added to the Object or
58651             // Function interface, since they have none by default. This is a bit of a leap of faith
58652             // that the user will not add any.
58653             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58654             if (constructSignatures.length) {
58655                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58656                     return resolveErrorCall(node);
58657                 }
58658                 // If the expression is a class of abstract type, then it cannot be instantiated.
58659                 // Note, only class declarations can be declared abstract.
58660                 // In the case of a merged class-module or class-interface declaration,
58661                 // only the class declaration node will have the Abstract flag set.
58662                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58663                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58664                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58665                     return resolveErrorCall(node);
58666                 }
58667                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58668             }
58669             // If expressionType's apparent type is an object type with no construct signatures but
58670             // one or more call signatures, the expression is processed as a function call. A compile-time
58671             // error occurs if the result of the function call is not Void. The type of the result of the
58672             // operation is Any. It is an error to have a Void this type.
58673             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58674             if (callSignatures.length) {
58675                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58676                 if (!noImplicitAny) {
58677                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58678                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58679                     }
58680                     if (getThisTypeOfSignature(signature) === voidType) {
58681                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58682                     }
58683                 }
58684                 return signature;
58685             }
58686             invocationError(node.expression, expressionType, 1 /* Construct */);
58687             return resolveErrorCall(node);
58688         }
58689         function typeHasProtectedAccessibleBase(target, type) {
58690             var baseTypes = getBaseTypes(type);
58691             if (!ts.length(baseTypes)) {
58692                 return false;
58693             }
58694             var firstBase = baseTypes[0];
58695             if (firstBase.flags & 2097152 /* Intersection */) {
58696                 var types = firstBase.types;
58697                 var mixinFlags = findMixins(types);
58698                 var i = 0;
58699                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58700                     var intersectionMember = _a[_i];
58701                     // We want to ignore mixin ctors
58702                     if (!mixinFlags[i]) {
58703                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58704                             if (intersectionMember.symbol === target) {
58705                                 return true;
58706                             }
58707                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58708                                 return true;
58709                             }
58710                         }
58711                     }
58712                     i++;
58713                 }
58714                 return false;
58715             }
58716             if (firstBase.symbol === target) {
58717                 return true;
58718             }
58719             return typeHasProtectedAccessibleBase(target, firstBase);
58720         }
58721         function isConstructorAccessible(node, signature) {
58722             if (!signature || !signature.declaration) {
58723                 return true;
58724             }
58725             var declaration = signature.declaration;
58726             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58727             // (1) Public constructors and (2) constructor functions are always accessible.
58728             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58729                 return true;
58730             }
58731             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58732             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58733             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58734             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58735                 var containingClass = ts.getContainingClass(node);
58736                 if (containingClass && modifiers & 16 /* Protected */) {
58737                     var containingType = getTypeOfNode(containingClass);
58738                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58739                         return true;
58740                     }
58741                 }
58742                 if (modifiers & 8 /* Private */) {
58743                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58744                 }
58745                 if (modifiers & 16 /* Protected */) {
58746                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58747                 }
58748                 return false;
58749             }
58750             return true;
58751         }
58752         function invocationErrorDetails(apparentType, kind) {
58753             var errorInfo;
58754             var isCall = kind === 0 /* Call */;
58755             var awaitedType = getAwaitedType(apparentType);
58756             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58757             if (apparentType.flags & 1048576 /* Union */) {
58758                 var types = apparentType.types;
58759                 var hasSignatures = false;
58760                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58761                     var constituent = types_18[_i];
58762                     var signatures = getSignaturesOfType(constituent, kind);
58763                     if (signatures.length !== 0) {
58764                         hasSignatures = true;
58765                         if (errorInfo) {
58766                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58767                             break;
58768                         }
58769                     }
58770                     else {
58771                         // Error on the first non callable constituent only
58772                         if (!errorInfo) {
58773                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58774                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58775                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58776                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58777                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58778                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58779                         }
58780                         if (hasSignatures) {
58781                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58782                             break;
58783                         }
58784                     }
58785                 }
58786                 if (!hasSignatures) {
58787                     errorInfo = ts.chainDiagnosticMessages(
58788                     /* detials */ undefined, isCall ?
58789                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58790                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58791                 }
58792                 if (!errorInfo) {
58793                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58794                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58795                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58796                 }
58797             }
58798             else {
58799                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58800                     ts.Diagnostics.Type_0_has_no_call_signatures :
58801                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58802             }
58803             return {
58804                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58805                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58806             };
58807         }
58808         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58809             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58810             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58811             if (relatedInfo) {
58812                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58813             }
58814             if (ts.isCallExpression(errorTarget.parent)) {
58815                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58816                 diagnostic.start = start;
58817                 diagnostic.length = length_7;
58818             }
58819             diagnostics.add(diagnostic);
58820             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
58821         }
58822         function invocationErrorRecovery(apparentType, kind, diagnostic) {
58823             if (!apparentType.symbol) {
58824                 return;
58825             }
58826             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
58827             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
58828             //  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
58829             if (importNode && !ts.isImportCall(importNode)) {
58830                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
58831                 if (!sigs || !sigs.length)
58832                     return;
58833                 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));
58834             }
58835         }
58836         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
58837             var tagType = checkExpression(node.tag);
58838             var apparentType = getApparentType(tagType);
58839             if (apparentType === errorType) {
58840                 // Another error has already been reported
58841                 return resolveErrorCall(node);
58842             }
58843             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58844             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58845             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
58846                 return resolveUntypedCall(node);
58847             }
58848             if (!callSignatures.length) {
58849                 invocationError(node.tag, apparentType, 0 /* Call */);
58850                 return resolveErrorCall(node);
58851             }
58852             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58853         }
58854         /**
58855          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
58856          */
58857         function getDiagnosticHeadMessageForDecoratorResolution(node) {
58858             switch (node.parent.kind) {
58859                 case 245 /* ClassDeclaration */:
58860                 case 214 /* ClassExpression */:
58861                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
58862                 case 156 /* Parameter */:
58863                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
58864                 case 159 /* PropertyDeclaration */:
58865                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
58866                 case 161 /* MethodDeclaration */:
58867                 case 163 /* GetAccessor */:
58868                 case 164 /* SetAccessor */:
58869                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
58870                 default:
58871                     return ts.Debug.fail();
58872             }
58873         }
58874         /**
58875          * Resolves a decorator as if it were a call expression.
58876          */
58877         function resolveDecorator(node, candidatesOutArray, checkMode) {
58878             var funcType = checkExpression(node.expression);
58879             var apparentType = getApparentType(funcType);
58880             if (apparentType === errorType) {
58881                 return resolveErrorCall(node);
58882             }
58883             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58884             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58885             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58886                 return resolveUntypedCall(node);
58887             }
58888             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
58889                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
58890                 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);
58891                 return resolveErrorCall(node);
58892             }
58893             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
58894             if (!callSignatures.length) {
58895                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
58896                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
58897                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
58898                 if (errorDetails.relatedMessage) {
58899                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
58900                 }
58901                 diagnostics.add(diag);
58902                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
58903                 return resolveErrorCall(node);
58904             }
58905             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
58906         }
58907         function createSignatureForJSXIntrinsic(node, result) {
58908             var namespace = getJsxNamespaceAt(node);
58909             var exports = namespace && getExportsOfSymbol(namespace);
58910             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
58911             // file would probably be preferable.
58912             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
58913             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
58914             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 */));
58915             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
58916             parameterSymbol.type = result;
58917             return createSignature(declaration, 
58918             /*typeParameters*/ undefined, 
58919             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
58920             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
58921         }
58922         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
58923             if (isJsxIntrinsicIdentifier(node.tagName)) {
58924                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
58925                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
58926                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
58927                 return fakeSignature;
58928             }
58929             var exprTypes = checkExpression(node.tagName);
58930             var apparentType = getApparentType(exprTypes);
58931             if (apparentType === errorType) {
58932                 return resolveErrorCall(node);
58933             }
58934             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
58935             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
58936                 return resolveUntypedCall(node);
58937             }
58938             if (signatures.length === 0) {
58939                 // We found no signatures at all, which is an error
58940                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
58941                 return resolveErrorCall(node);
58942             }
58943             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
58944         }
58945         /**
58946          * Sometimes, we have a decorator that could accept zero arguments,
58947          * but is receiving too many arguments as part of the decorator invocation.
58948          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
58949          */
58950         function isPotentiallyUncalledDecorator(decorator, signatures) {
58951             return signatures.length && ts.every(signatures, function (signature) {
58952                 return signature.minArgumentCount === 0 &&
58953                     !signatureHasRestParameter(signature) &&
58954                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
58955             });
58956         }
58957         function resolveSignature(node, candidatesOutArray, checkMode) {
58958             switch (node.kind) {
58959                 case 196 /* CallExpression */:
58960                     return resolveCallExpression(node, candidatesOutArray, checkMode);
58961                 case 197 /* NewExpression */:
58962                     return resolveNewExpression(node, candidatesOutArray, checkMode);
58963                 case 198 /* TaggedTemplateExpression */:
58964                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
58965                 case 157 /* Decorator */:
58966                     return resolveDecorator(node, candidatesOutArray, checkMode);
58967                 case 268 /* JsxOpeningElement */:
58968                 case 267 /* JsxSelfClosingElement */:
58969                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
58970             }
58971             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
58972         }
58973         /**
58974          * Resolve a signature of a given call-like expression.
58975          * @param node a call-like expression to try resolve a signature for
58976          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
58977          *                           the function will fill it up with appropriate candidate signatures
58978          * @return a signature of the call-like expression or undefined if one can't be found
58979          */
58980         function getResolvedSignature(node, candidatesOutArray, checkMode) {
58981             var links = getNodeLinks(node);
58982             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
58983             // However, it is possible that either candidatesOutArray was not passed in the first time,
58984             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
58985             // to correctly fill the candidatesOutArray.
58986             var cached = links.resolvedSignature;
58987             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
58988                 return cached;
58989             }
58990             links.resolvedSignature = resolvingSignature;
58991             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
58992             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
58993             // resolution should be deferred.
58994             if (result !== resolvingSignature) {
58995                 // If signature resolution originated in control flow type analysis (for example to compute the
58996                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
58997                 // types from the control flow analysis.
58998                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
58999             }
59000             return result;
59001         }
59002         /**
59003          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59004          * file.
59005          */
59006         function isJSConstructor(node) {
59007             if (!node || !ts.isInJSFile(node)) {
59008                 return false;
59009             }
59010             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59011                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59012                     undefined;
59013             if (func) {
59014                 // If the node has a @class tag, treat it like a constructor.
59015                 if (ts.getJSDocClassTag(node))
59016                     return true;
59017                 // If the symbol of the node has members, treat it like a constructor.
59018                 var symbol = getSymbolOfNode(func);
59019                 return !!symbol && ts.hasEntries(symbol.members);
59020             }
59021             return false;
59022         }
59023         function mergeJSSymbols(target, source) {
59024             if (source) {
59025                 var links = getSymbolLinks(source);
59026                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59027                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59028                     inferred.exports = inferred.exports || ts.createSymbolTable();
59029                     inferred.members = inferred.members || ts.createSymbolTable();
59030                     inferred.flags |= source.flags & 32 /* Class */;
59031                     if (ts.hasEntries(source.exports)) {
59032                         mergeSymbolTable(inferred.exports, source.exports);
59033                     }
59034                     if (ts.hasEntries(source.members)) {
59035                         mergeSymbolTable(inferred.members, source.members);
59036                     }
59037                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59038                     return inferred;
59039                 }
59040                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59041             }
59042         }
59043         function getAssignedClassSymbol(decl) {
59044             var assignmentSymbol = decl && decl.parent &&
59045                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59046                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59047                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59048             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59049             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59050             return init ? getSymbolOfNode(init) : undefined;
59051         }
59052         function getAssignedJSPrototype(node) {
59053             if (!node.parent) {
59054                 return false;
59055             }
59056             var parent = node.parent;
59057             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59058                 parent = parent.parent;
59059             }
59060             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59061                 var right = ts.getInitializerOfBinaryExpression(parent);
59062                 return ts.isObjectLiteralExpression(right) && right;
59063             }
59064         }
59065         /**
59066          * Syntactically and semantically checks a call or new expression.
59067          * @param node The call/new expression to be checked.
59068          * @returns On success, the expression's signature's return type. On failure, anyType.
59069          */
59070         function checkCallExpression(node, checkMode) {
59071             if (!checkGrammarTypeArguments(node, node.typeArguments))
59072                 checkGrammarArguments(node.arguments);
59073             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59074             if (signature === resolvingSignature) {
59075                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59076                 // returns a function type. We defer checking and return nonInferrableType.
59077                 return nonInferrableType;
59078             }
59079             if (node.expression.kind === 102 /* SuperKeyword */) {
59080                 return voidType;
59081             }
59082             if (node.kind === 197 /* NewExpression */) {
59083                 var declaration = signature.declaration;
59084                 if (declaration &&
59085                     declaration.kind !== 162 /* Constructor */ &&
59086                     declaration.kind !== 166 /* ConstructSignature */ &&
59087                     declaration.kind !== 171 /* ConstructorType */ &&
59088                     !ts.isJSDocConstructSignature(declaration) &&
59089                     !isJSConstructor(declaration)) {
59090                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59091                     if (noImplicitAny) {
59092                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59093                     }
59094                     return anyType;
59095                 }
59096             }
59097             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59098             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59099                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59100             }
59101             var returnType = getReturnTypeOfSignature(signature);
59102             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59103             // as a fresh unique symbol literal type.
59104             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59105                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59106             }
59107             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59108                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59109                 if (!ts.isDottedName(node.expression)) {
59110                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59111                 }
59112                 else if (!getEffectsSignature(node)) {
59113                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59114                     getTypeOfDottedName(node.expression, diagnostic);
59115                 }
59116             }
59117             if (ts.isInJSFile(node)) {
59118                 var decl = ts.getDeclarationOfExpando(node);
59119                 if (decl) {
59120                     var jsSymbol = getSymbolOfNode(decl);
59121                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59122                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59123                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59124                         return getIntersectionType([returnType, jsAssignmentType]);
59125                     }
59126                 }
59127             }
59128             return returnType;
59129         }
59130         function isSymbolOrSymbolForCall(node) {
59131             if (!ts.isCallExpression(node))
59132                 return false;
59133             var left = node.expression;
59134             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59135                 left = left.expression;
59136             }
59137             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59138                 return false;
59139             }
59140             // make sure `Symbol` is the global symbol
59141             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59142             if (!globalESSymbol) {
59143                 return false;
59144             }
59145             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59146         }
59147         function checkImportCallExpression(node) {
59148             // Check grammar of dynamic import
59149             if (!checkGrammarArguments(node.arguments))
59150                 checkGrammarImportCallExpression(node);
59151             if (node.arguments.length === 0) {
59152                 return createPromiseReturnType(node, anyType);
59153             }
59154             var specifier = node.arguments[0];
59155             var specifierType = checkExpressionCached(specifier);
59156             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59157             for (var i = 1; i < node.arguments.length; ++i) {
59158                 checkExpressionCached(node.arguments[i]);
59159             }
59160             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59161                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59162             }
59163             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59164             var moduleSymbol = resolveExternalModuleName(node, specifier);
59165             if (moduleSymbol) {
59166                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59167                 if (esModuleSymbol) {
59168                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59169                 }
59170             }
59171             return createPromiseReturnType(node, anyType);
59172         }
59173         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59174             if (allowSyntheticDefaultImports && type && type !== errorType) {
59175                 var synthType = type;
59176                 if (!synthType.syntheticType) {
59177                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59178                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59179                     if (hasSyntheticDefault) {
59180                         var memberTable = ts.createSymbolTable();
59181                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59182                         newSymbol.nameType = getLiteralType("default");
59183                         newSymbol.target = resolveSymbol(symbol);
59184                         memberTable.set("default" /* Default */, newSymbol);
59185                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59186                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59187                         anonymousSymbol.type = defaultContainingObject;
59188                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59189                     }
59190                     else {
59191                         synthType.syntheticType = type;
59192                     }
59193                 }
59194                 return synthType.syntheticType;
59195             }
59196             return type;
59197         }
59198         function isCommonJsRequire(node) {
59199             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59200                 return false;
59201             }
59202             // Make sure require is not a local function
59203             if (!ts.isIdentifier(node.expression))
59204                 return ts.Debug.fail();
59205             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59206             if (resolvedRequire === requireSymbol) {
59207                 return true;
59208             }
59209             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59210             if (resolvedRequire.flags & 2097152 /* Alias */) {
59211                 return false;
59212             }
59213             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59214                 ? 244 /* FunctionDeclaration */
59215                 : resolvedRequire.flags & 3 /* Variable */
59216                     ? 242 /* VariableDeclaration */
59217                     : 0 /* Unknown */;
59218             if (targetDeclarationKind !== 0 /* Unknown */) {
59219                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59220                 // function/variable declaration should be ambient
59221                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59222             }
59223             return false;
59224         }
59225         function checkTaggedTemplateExpression(node) {
59226             if (!checkGrammarTaggedTemplateChain(node))
59227                 checkGrammarTypeArguments(node, node.typeArguments);
59228             if (languageVersion < 2 /* ES2015 */) {
59229                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59230             }
59231             return getReturnTypeOfSignature(getResolvedSignature(node));
59232         }
59233         function checkAssertion(node) {
59234             return checkAssertionWorker(node, node.type, node.expression);
59235         }
59236         function isValidConstAssertionArgument(node) {
59237             switch (node.kind) {
59238                 case 10 /* StringLiteral */:
59239                 case 14 /* NoSubstitutionTemplateLiteral */:
59240                 case 8 /* NumericLiteral */:
59241                 case 9 /* BigIntLiteral */:
59242                 case 106 /* TrueKeyword */:
59243                 case 91 /* FalseKeyword */:
59244                 case 192 /* ArrayLiteralExpression */:
59245                 case 193 /* ObjectLiteralExpression */:
59246                     return true;
59247                 case 200 /* ParenthesizedExpression */:
59248                     return isValidConstAssertionArgument(node.expression);
59249                 case 207 /* PrefixUnaryExpression */:
59250                     var op = node.operator;
59251                     var arg = node.operand;
59252                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59253                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59254                 case 194 /* PropertyAccessExpression */:
59255                 case 195 /* ElementAccessExpression */:
59256                     var expr = node.expression;
59257                     if (ts.isIdentifier(expr)) {
59258                         var symbol = getSymbolAtLocation(expr);
59259                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59260                             symbol = resolveAlias(symbol);
59261                         }
59262                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59263                     }
59264             }
59265             return false;
59266         }
59267         function checkAssertionWorker(errNode, type, expression, checkMode) {
59268             var exprType = checkExpression(expression, checkMode);
59269             if (ts.isConstTypeReference(type)) {
59270                 if (!isValidConstAssertionArgument(expression)) {
59271                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59272                 }
59273                 return getRegularTypeOfLiteralType(exprType);
59274             }
59275             checkSourceElement(type);
59276             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59277             var targetType = getTypeFromTypeNode(type);
59278             if (produceDiagnostics && targetType !== errorType) {
59279                 var widenedType = getWidenedType(exprType);
59280                 if (!isTypeComparableTo(targetType, widenedType)) {
59281                     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);
59282                 }
59283             }
59284             return targetType;
59285         }
59286         function checkNonNullChain(node) {
59287             var leftType = checkExpression(node.expression);
59288             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59289             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59290         }
59291         function checkNonNullAssertion(node) {
59292             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59293                 getNonNullableType(checkExpression(node.expression));
59294         }
59295         function checkMetaProperty(node) {
59296             checkGrammarMetaProperty(node);
59297             if (node.keywordToken === 99 /* NewKeyword */) {
59298                 return checkNewTargetMetaProperty(node);
59299             }
59300             if (node.keywordToken === 96 /* ImportKeyword */) {
59301                 return checkImportMetaProperty(node);
59302             }
59303             return ts.Debug.assertNever(node.keywordToken);
59304         }
59305         function checkNewTargetMetaProperty(node) {
59306             var container = ts.getNewTargetContainer(node);
59307             if (!container) {
59308                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59309                 return errorType;
59310             }
59311             else if (container.kind === 162 /* Constructor */) {
59312                 var symbol = getSymbolOfNode(container.parent);
59313                 return getTypeOfSymbol(symbol);
59314             }
59315             else {
59316                 var symbol = getSymbolOfNode(container);
59317                 return getTypeOfSymbol(symbol);
59318             }
59319         }
59320         function checkImportMetaProperty(node) {
59321             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59322                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59323             }
59324             var file = ts.getSourceFileOfNode(node);
59325             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59326             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59327             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59328         }
59329         function getTypeOfParameter(symbol) {
59330             var type = getTypeOfSymbol(symbol);
59331             if (strictNullChecks) {
59332                 var declaration = symbol.valueDeclaration;
59333                 if (declaration && ts.hasInitializer(declaration)) {
59334                     return getOptionalType(type);
59335                 }
59336             }
59337             return type;
59338         }
59339         function getParameterNameAtPosition(signature, pos) {
59340             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59341             if (pos < paramCount) {
59342                 return signature.parameters[pos].escapedName;
59343             }
59344             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59345             var restType = getTypeOfSymbol(restParameter);
59346             if (isTupleType(restType)) {
59347                 var associatedNames = restType.target.associatedNames;
59348                 var index = pos - paramCount;
59349                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59350             }
59351             return restParameter.escapedName;
59352         }
59353         function getTypeAtPosition(signature, pos) {
59354             return tryGetTypeAtPosition(signature, pos) || anyType;
59355         }
59356         function tryGetTypeAtPosition(signature, pos) {
59357             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59358             if (pos < paramCount) {
59359                 return getTypeOfParameter(signature.parameters[pos]);
59360             }
59361             if (signatureHasRestParameter(signature)) {
59362                 // We want to return the value undefined for an out of bounds parameter position,
59363                 // so we need to check bounds here before calling getIndexedAccessType (which
59364                 // otherwise would return the type 'undefined').
59365                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59366                 var index = pos - paramCount;
59367                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59368                     return getIndexedAccessType(restType, getLiteralType(index));
59369                 }
59370             }
59371             return undefined;
59372         }
59373         function getRestTypeAtPosition(source, pos) {
59374             var paramCount = getParameterCount(source);
59375             var restType = getEffectiveRestType(source);
59376             var nonRestCount = paramCount - (restType ? 1 : 0);
59377             if (restType && pos === nonRestCount) {
59378                 return restType;
59379             }
59380             var types = [];
59381             var names = [];
59382             for (var i = pos; i < nonRestCount; i++) {
59383                 types.push(getTypeAtPosition(source, i));
59384                 names.push(getParameterNameAtPosition(source, i));
59385             }
59386             if (restType) {
59387                 types.push(getIndexedAccessType(restType, numberType));
59388                 names.push(getParameterNameAtPosition(source, nonRestCount));
59389             }
59390             var minArgumentCount = getMinArgumentCount(source);
59391             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59392             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59393         }
59394         function getParameterCount(signature) {
59395             var length = signature.parameters.length;
59396             if (signatureHasRestParameter(signature)) {
59397                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59398                 if (isTupleType(restType)) {
59399                     return length + getTypeArguments(restType).length - 1;
59400                 }
59401             }
59402             return length;
59403         }
59404         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59405             if (signatureHasRestParameter(signature)) {
59406                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59407                 if (isTupleType(restType)) {
59408                     var minLength = restType.target.minLength;
59409                     if (minLength > 0) {
59410                         return signature.parameters.length - 1 + minLength;
59411                     }
59412                 }
59413             }
59414             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59415                 return 0;
59416             }
59417             return signature.minArgumentCount;
59418         }
59419         function hasEffectiveRestParameter(signature) {
59420             if (signatureHasRestParameter(signature)) {
59421                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59422                 return !isTupleType(restType) || restType.target.hasRestElement;
59423             }
59424             return false;
59425         }
59426         function getEffectiveRestType(signature) {
59427             if (signatureHasRestParameter(signature)) {
59428                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59429                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59430             }
59431             return undefined;
59432         }
59433         function getNonArrayRestType(signature) {
59434             var restType = getEffectiveRestType(signature);
59435             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59436         }
59437         function getTypeOfFirstParameterOfSignature(signature) {
59438             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59439         }
59440         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59441             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59442         }
59443         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59444             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59445             for (var i = 0; i < len; i++) {
59446                 var declaration = signature.parameters[i].valueDeclaration;
59447                 if (declaration.type) {
59448                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59449                     if (typeNode) {
59450                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59451                     }
59452                 }
59453             }
59454             var restType = getEffectiveRestType(context);
59455             if (restType && restType.flags & 262144 /* TypeParameter */) {
59456                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59457                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59458                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59459                 assignContextualParameterTypes(signature, instantiatedContext);
59460                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59461                 // rest parameter.
59462                 var restPos = getParameterCount(context) - 1;
59463                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59464             }
59465         }
59466         function assignContextualParameterTypes(signature, context) {
59467             signature.typeParameters = context.typeParameters;
59468             if (context.thisParameter) {
59469                 var parameter = signature.thisParameter;
59470                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59471                     if (!parameter) {
59472                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59473                     }
59474                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59475                 }
59476             }
59477             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59478             for (var i = 0; i < len; i++) {
59479                 var parameter = signature.parameters[i];
59480                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59481                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59482                     assignParameterType(parameter, contextualParameterType);
59483                 }
59484             }
59485             if (signatureHasRestParameter(signature)) {
59486                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59487                 var parameter = ts.last(signature.parameters);
59488                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59489                     var contextualParameterType = getRestTypeAtPosition(context, len);
59490                     assignParameterType(parameter, contextualParameterType);
59491                 }
59492             }
59493         }
59494         function assignNonContextualParameterTypes(signature) {
59495             if (signature.thisParameter) {
59496                 assignParameterType(signature.thisParameter);
59497             }
59498             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59499                 var parameter = _a[_i];
59500                 assignParameterType(parameter);
59501             }
59502         }
59503         function assignParameterType(parameter, type) {
59504             var links = getSymbolLinks(parameter);
59505             if (!links.type) {
59506                 var declaration = parameter.valueDeclaration;
59507                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59508                 if (declaration.name.kind !== 75 /* Identifier */) {
59509                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59510                     if (links.type === unknownType) {
59511                         links.type = getTypeFromBindingPattern(declaration.name);
59512                     }
59513                     assignBindingElementTypes(declaration.name);
59514                 }
59515             }
59516         }
59517         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59518         // the destructured type into the contained binding elements.
59519         function assignBindingElementTypes(pattern) {
59520             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59521                 var element = _a[_i];
59522                 if (!ts.isOmittedExpression(element)) {
59523                     if (element.name.kind === 75 /* Identifier */) {
59524                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59525                     }
59526                     else {
59527                         assignBindingElementTypes(element.name);
59528                     }
59529                 }
59530             }
59531         }
59532         function createPromiseType(promisedType) {
59533             // creates a `Promise<T>` type where `T` is the promisedType argument
59534             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59535             if (globalPromiseType !== emptyGenericType) {
59536                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59537                 promisedType = getAwaitedType(promisedType) || unknownType;
59538                 return createTypeReference(globalPromiseType, [promisedType]);
59539             }
59540             return unknownType;
59541         }
59542         function createPromiseLikeType(promisedType) {
59543             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59544             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59545             if (globalPromiseLikeType !== emptyGenericType) {
59546                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59547                 promisedType = getAwaitedType(promisedType) || unknownType;
59548                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59549             }
59550             return unknownType;
59551         }
59552         function createPromiseReturnType(func, promisedType) {
59553             var promiseType = createPromiseType(promisedType);
59554             if (promiseType === unknownType) {
59555                 error(func, ts.isImportCall(func) ?
59556                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59557                     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);
59558                 return errorType;
59559             }
59560             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59561                 error(func, ts.isImportCall(func) ?
59562                     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 :
59563                     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);
59564             }
59565             return promiseType;
59566         }
59567         function getReturnTypeFromBody(func, checkMode) {
59568             if (!func.body) {
59569                 return errorType;
59570             }
59571             var functionFlags = ts.getFunctionFlags(func);
59572             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59573             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59574             var returnType;
59575             var yieldType;
59576             var nextType;
59577             var fallbackReturnType = voidType;
59578             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59579                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59580                 if (isAsync) {
59581                     // From within an async function you can return either a non-promise value or a promise. Any
59582                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59583                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59584                     // the native Promise<T> type later in this function.
59585                     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);
59586                 }
59587             }
59588             else if (isGenerator) { // Generator or AsyncGenerator function
59589                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59590                 if (!returnTypes) {
59591                     fallbackReturnType = neverType;
59592                 }
59593                 else if (returnTypes.length > 0) {
59594                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59595                 }
59596                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59597                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59598                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59599             }
59600             else { // Async or normal function
59601                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59602                 if (!types) {
59603                     // For an async function, the return type will not be never, but rather a Promise for never.
59604                     return functionFlags & 2 /* Async */
59605                         ? createPromiseReturnType(func, neverType) // Async function
59606                         : neverType; // Normal function
59607                 }
59608                 if (types.length === 0) {
59609                     // For an async function, the return type will not be void, but rather a Promise for void.
59610                     return functionFlags & 2 /* Async */
59611                         ? createPromiseReturnType(func, voidType) // Async function
59612                         : voidType; // Normal function
59613                 }
59614                 // Return a union of the return expression types.
59615                 returnType = getUnionType(types, 2 /* Subtype */);
59616             }
59617             if (returnType || yieldType || nextType) {
59618                 if (yieldType)
59619                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59620                 if (returnType)
59621                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59622                 if (nextType)
59623                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59624                 if (returnType && isUnitType(returnType) ||
59625                     yieldType && isUnitType(yieldType) ||
59626                     nextType && isUnitType(nextType)) {
59627                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59628                     var contextualType = !contextualSignature ? undefined :
59629                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59630                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59631                     if (isGenerator) {
59632                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59633                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59634                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59635                     }
59636                     else {
59637                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59638                     }
59639                 }
59640                 if (yieldType)
59641                     yieldType = getWidenedType(yieldType);
59642                 if (returnType)
59643                     returnType = getWidenedType(returnType);
59644                 if (nextType)
59645                     nextType = getWidenedType(nextType);
59646             }
59647             if (isGenerator) {
59648                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59649             }
59650             else {
59651                 // From within an async function you can return either a non-promise value or a promise. Any
59652                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59653                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59654                 return isAsync
59655                     ? createPromiseType(returnType || fallbackReturnType)
59656                     : returnType || fallbackReturnType;
59657             }
59658         }
59659         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59660             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59661             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59662             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59663             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59664             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59665             if (globalGeneratorType === emptyGenericType) {
59666                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59667                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59668                 // nextType.
59669                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59670                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59671                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59672                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59673                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59674                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59675                     if (globalType !== emptyGenericType) {
59676                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59677                     }
59678                     // The global IterableIterator type doesn't exist, so report an error
59679                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59680                     return emptyObjectType;
59681                 }
59682                 // The global Generator type doesn't exist, so report an error
59683                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59684                 return emptyObjectType;
59685             }
59686             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59687         }
59688         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59689             var yieldTypes = [];
59690             var nextTypes = [];
59691             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59692             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59693                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59694                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59695                 var nextType;
59696                 if (yieldExpression.asteriskToken) {
59697                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59698                     nextType = iterationTypes && iterationTypes.nextType;
59699                 }
59700                 else {
59701                     nextType = getContextualType(yieldExpression);
59702                 }
59703                 if (nextType)
59704                     ts.pushIfUnique(nextTypes, nextType);
59705             });
59706             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59707         }
59708         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59709             var errorNode = node.expression || node;
59710             // A `yield*` expression effectively yields everything that its operand yields
59711             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59712             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59713                 ? 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
59714                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59715         }
59716         /**
59717          * Collect the TypeFacts learned from a typeof switch with
59718          * total clauses `witnesses`, and the active clause ranging
59719          * from `start` to `end`. Parameter `hasDefault` denotes
59720          * whether the active clause contains a default clause.
59721          */
59722         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59723             var facts = 0 /* None */;
59724             // When in the default we only collect inequality facts
59725             // because default is 'in theory' a set of infinite
59726             // equalities.
59727             if (hasDefault) {
59728                 // Value is not equal to any types after the active clause.
59729                 for (var i = end; i < witnesses.length; i++) {
59730                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59731                 }
59732                 // Remove inequalities for types that appear in the
59733                 // active clause because they appear before other
59734                 // types collected so far.
59735                 for (var i = start; i < end; i++) {
59736                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59737                 }
59738                 // Add inequalities for types before the active clause unconditionally.
59739                 for (var i = 0; i < start; i++) {
59740                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59741                 }
59742             }
59743             // When in an active clause without default the set of
59744             // equalities is finite.
59745             else {
59746                 // Add equalities for all types in the active clause.
59747                 for (var i = start; i < end; i++) {
59748                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59749                 }
59750                 // Remove equalities for types that appear before the
59751                 // active clause.
59752                 for (var i = 0; i < start; i++) {
59753                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59754                 }
59755             }
59756             return facts;
59757         }
59758         function isExhaustiveSwitchStatement(node) {
59759             var links = getNodeLinks(node);
59760             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59761         }
59762         function computeExhaustiveSwitchStatement(node) {
59763             if (node.expression.kind === 204 /* TypeOfExpression */) {
59764                 var operandType = getTypeOfExpression(node.expression.expression);
59765                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59766                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59767                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59768                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59769                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59770             }
59771             var type = getTypeOfExpression(node.expression);
59772             if (!isLiteralType(type)) {
59773                 return false;
59774             }
59775             var switchTypes = getSwitchClauseTypes(node);
59776             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59777                 return false;
59778             }
59779             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59780         }
59781         function functionHasImplicitReturn(func) {
59782             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59783         }
59784         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59785         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59786             var functionFlags = ts.getFunctionFlags(func);
59787             var aggregatedTypes = [];
59788             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59789             var hasReturnOfTypeNever = false;
59790             ts.forEachReturnStatement(func.body, function (returnStatement) {
59791                 var expr = returnStatement.expression;
59792                 if (expr) {
59793                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59794                     if (functionFlags & 2 /* Async */) {
59795                         // From within an async function you can return either a non-promise value or a promise. Any
59796                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59797                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59798                         // the native Promise<T> type by the caller.
59799                         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);
59800                     }
59801                     if (type.flags & 131072 /* Never */) {
59802                         hasReturnOfTypeNever = true;
59803                     }
59804                     ts.pushIfUnique(aggregatedTypes, type);
59805                 }
59806                 else {
59807                     hasReturnWithNoExpression = true;
59808                 }
59809             });
59810             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59811                 return undefined;
59812             }
59813             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59814                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59815                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59816                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59817             }
59818             return aggregatedTypes;
59819         }
59820         function mayReturnNever(func) {
59821             switch (func.kind) {
59822                 case 201 /* FunctionExpression */:
59823                 case 202 /* ArrowFunction */:
59824                     return true;
59825                 case 161 /* MethodDeclaration */:
59826                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
59827                 default:
59828                     return false;
59829             }
59830         }
59831         /**
59832          * TypeScript Specification 1.0 (6.3) - July 2014
59833          *   An explicitly typed function whose return type isn't the Void type,
59834          *   the Any type, or a union type containing the Void or Any type as a constituent
59835          *   must have at least one return statement somewhere in its body.
59836          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
59837          *
59838          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
59839          */
59840         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
59841             if (!produceDiagnostics) {
59842                 return;
59843             }
59844             var functionFlags = ts.getFunctionFlags(func);
59845             var type = returnType && unwrapReturnType(returnType, functionFlags);
59846             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
59847             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
59848                 return;
59849             }
59850             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
59851             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
59852             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
59853                 return;
59854             }
59855             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
59856             if (type && type.flags & 131072 /* Never */) {
59857                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
59858             }
59859             else if (type && !hasExplicitReturn) {
59860                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
59861                 // this function does not conform to the specification.
59862                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
59863                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
59864             }
59865             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
59866                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
59867             }
59868             else if (compilerOptions.noImplicitReturns) {
59869                 if (!type) {
59870                     // If return type annotation is omitted check if function has any explicit return statements.
59871                     // If it does not have any - its inferred return type is void - don't do any checks.
59872                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
59873                     if (!hasExplicitReturn) {
59874                         return;
59875                     }
59876                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
59877                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
59878                         return;
59879                     }
59880                 }
59881                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
59882             }
59883         }
59884         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59885             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59886             checkNodeDeferred(node);
59887             // The identityMapper object is used to indicate that function expressions are wildcards
59888             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
59889                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
59890                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
59891                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
59892                     var contextualSignature = getContextualSignature(node);
59893                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
59894                         var links = getNodeLinks(node);
59895                         if (links.contextFreeType) {
59896                             return links.contextFreeType;
59897                         }
59898                         var returnType = getReturnTypeFromBody(node, checkMode);
59899                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
59900                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
59901                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
59902                         return links.contextFreeType = returnOnlyType;
59903                     }
59904                 }
59905                 return anyFunctionType;
59906             }
59907             // Grammar checking
59908             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
59909             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
59910                 checkGrammarForGenerator(node);
59911             }
59912             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
59913             return getTypeOfSymbol(getSymbolOfNode(node));
59914         }
59915         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59916             var links = getNodeLinks(node);
59917             // Check if function expression is contextually typed and assign parameter types if so.
59918             if (!(links.flags & 1024 /* ContextChecked */)) {
59919                 var contextualSignature = getContextualSignature(node);
59920                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
59921                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
59922                 // already assigned contextual types.
59923                 if (!(links.flags & 1024 /* ContextChecked */)) {
59924                     links.flags |= 1024 /* ContextChecked */;
59925                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
59926                     if (!signature) {
59927                         return;
59928                     }
59929                     if (isContextSensitive(node)) {
59930                         if (contextualSignature) {
59931                             var inferenceContext = getInferenceContext(node);
59932                             if (checkMode && checkMode & 2 /* Inferential */) {
59933                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
59934                             }
59935                             var instantiatedContextualSignature = inferenceContext ?
59936                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
59937                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
59938                         }
59939                         else {
59940                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
59941                             assignNonContextualParameterTypes(signature);
59942                         }
59943                     }
59944                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
59945                         var returnType = getReturnTypeFromBody(node, checkMode);
59946                         if (!signature.resolvedReturnType) {
59947                             signature.resolvedReturnType = returnType;
59948                         }
59949                     }
59950                     checkSignatureDeclaration(node);
59951                 }
59952             }
59953         }
59954         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
59955             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59956             var functionFlags = ts.getFunctionFlags(node);
59957             var returnType = getReturnTypeFromAnnotation(node);
59958             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
59959             if (node.body) {
59960                 if (!ts.getEffectiveReturnTypeNode(node)) {
59961                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
59962                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
59963                     // of a function. Because checking of function expression bodies is deferred, there was never an
59964                     // appropriate time to do this during the main walk of the file (see the comment at the top of
59965                     // checkFunctionExpressionBodies). So it must be done now.
59966                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
59967                 }
59968                 if (node.body.kind === 223 /* Block */) {
59969                     checkSourceElement(node.body);
59970                 }
59971                 else {
59972                     // From within an async function you can return either a non-promise value or a promise. Any
59973                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
59974                     // should not be checking assignability of a promise to the return type. Instead, we need to
59975                     // check assignability of the awaited type of the expression body against the promised type of
59976                     // its return type annotation.
59977                     var exprType = checkExpression(node.body);
59978                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
59979                     if (returnOrPromisedType) {
59980                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
59981                             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);
59982                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
59983                         }
59984                         else { // Normal function
59985                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
59986                         }
59987                     }
59988                 }
59989             }
59990         }
59991         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
59992             if (isAwaitValid === void 0) { isAwaitValid = false; }
59993             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
59994                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
59995                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
59996                 return false;
59997             }
59998             return true;
59999         }
60000         function isReadonlyAssignmentDeclaration(d) {
60001             if (!ts.isCallExpression(d)) {
60002                 return false;
60003             }
60004             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60005                 return false;
60006             }
60007             var objectLitType = checkExpressionCached(d.arguments[2]);
60008             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60009             if (valueType) {
60010                 var writableProp = getPropertyOfType(objectLitType, "writable");
60011                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60012                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60013                     return true;
60014                 }
60015                 // We include this definition whereupon we walk back and check the type at the declaration because
60016                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60017                 // argument types, should the type be contextualized by the call itself.
60018                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60019                     var initializer = writableProp.valueDeclaration.initializer;
60020                     var rawOriginalType = checkExpression(initializer);
60021                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60022                         return true;
60023                     }
60024                 }
60025                 return false;
60026             }
60027             var setProp = getPropertyOfType(objectLitType, "set");
60028             return !setProp;
60029         }
60030         function isReadonlySymbol(symbol) {
60031             // The following symbols are considered read-only:
60032             // Properties with a 'readonly' modifier
60033             // Variables declared with 'const'
60034             // Get accessors without matching set accessors
60035             // Enum members
60036             // Object.defineProperty assignments with writable false or no setter
60037             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60038             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60039                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60040                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60041                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60042                 symbol.flags & 8 /* EnumMember */ ||
60043                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60044         }
60045         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60046             var _a, _b;
60047             if (assignmentKind === 0 /* None */) {
60048                 // no assigment means it doesn't matter whether the entity is readonly
60049                 return false;
60050             }
60051             if (isReadonlySymbol(symbol)) {
60052                 // Allow assignments to readonly properties within constructors of the same class declaration.
60053                 if (symbol.flags & 4 /* Property */ &&
60054                     ts.isAccessExpression(expr) &&
60055                     expr.expression.kind === 104 /* ThisKeyword */) {
60056                     // Look for if this is the constructor for the class that `symbol` is a property of.
60057                     var ctor = ts.getContainingFunction(expr);
60058                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60059                         return true;
60060                     }
60061                     if (symbol.valueDeclaration) {
60062                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60063                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60064                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60065                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60066                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60067                         var isWriteableSymbol = isLocalPropertyDeclaration
60068                             || isLocalParameterProperty
60069                             || isLocalThisPropertyAssignment
60070                             || isLocalThisPropertyAssignmentConstructorFunction;
60071                         return !isWriteableSymbol;
60072                     }
60073                 }
60074                 return true;
60075             }
60076             if (ts.isAccessExpression(expr)) {
60077                 // references through namespace import should be readonly
60078                 var node = ts.skipParentheses(expr.expression);
60079                 if (node.kind === 75 /* Identifier */) {
60080                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60081                     if (symbol_2.flags & 2097152 /* Alias */) {
60082                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60083                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60084                     }
60085                 }
60086             }
60087             return false;
60088         }
60089         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60090             // References are combinations of identifiers, parentheses, and property accesses.
60091             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60092             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60093                 error(expr, invalidReferenceMessage);
60094                 return false;
60095             }
60096             if (node.flags & 32 /* OptionalChain */) {
60097                 error(expr, invalidOptionalChainMessage);
60098                 return false;
60099             }
60100             return true;
60101         }
60102         function checkDeleteExpression(node) {
60103             checkExpression(node.expression);
60104             var expr = ts.skipParentheses(node.expression);
60105             if (!ts.isAccessExpression(expr)) {
60106                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60107                 return booleanType;
60108             }
60109             // eslint-disable-next-line
60110             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60111                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60112             }
60113             var links = getNodeLinks(expr);
60114             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60115             if (symbol && isReadonlySymbol(symbol)) {
60116                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60117             }
60118             return booleanType;
60119         }
60120         function checkTypeOfExpression(node) {
60121             checkExpression(node.expression);
60122             return typeofType;
60123         }
60124         function checkVoidExpression(node) {
60125             checkExpression(node.expression);
60126             return undefinedWideningType;
60127         }
60128         function isTopLevelAwait(node) {
60129             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60130             return ts.isSourceFile(container);
60131         }
60132         function checkAwaitExpression(node) {
60133             // Grammar checking
60134             if (produceDiagnostics) {
60135                 if (!(node.flags & 32768 /* AwaitContext */)) {
60136                     if (isTopLevelAwait(node)) {
60137                         var sourceFile = ts.getSourceFileOfNode(node);
60138                         if (!hasParseDiagnostics(sourceFile)) {
60139                             var span = void 0;
60140                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60141                                 if (!span)
60142                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60143                                 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);
60144                                 diagnostics.add(diagnostic);
60145                             }
60146                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60147                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60148                                 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);
60149                                 diagnostics.add(diagnostic);
60150                             }
60151                         }
60152                     }
60153                     else {
60154                         // use of 'await' in non-async function
60155                         var sourceFile = ts.getSourceFileOfNode(node);
60156                         if (!hasParseDiagnostics(sourceFile)) {
60157                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60158                             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);
60159                             var func = ts.getContainingFunction(node);
60160                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60161                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60162                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60163                             }
60164                             diagnostics.add(diagnostic);
60165                         }
60166                     }
60167                 }
60168                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60169                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60170                 }
60171             }
60172             var operandType = checkExpression(node.expression);
60173             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);
60174             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60175                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60176             }
60177             return awaitedType;
60178         }
60179         function checkPrefixUnaryExpression(node) {
60180             var operandType = checkExpression(node.operand);
60181             if (operandType === silentNeverType) {
60182                 return silentNeverType;
60183             }
60184             switch (node.operand.kind) {
60185                 case 8 /* NumericLiteral */:
60186                     switch (node.operator) {
60187                         case 40 /* MinusToken */:
60188                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60189                         case 39 /* PlusToken */:
60190                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60191                     }
60192                     break;
60193                 case 9 /* BigIntLiteral */:
60194                     if (node.operator === 40 /* MinusToken */) {
60195                         return getFreshTypeOfLiteralType(getLiteralType({
60196                             negative: true,
60197                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60198                         }));
60199                     }
60200             }
60201             switch (node.operator) {
60202                 case 39 /* PlusToken */:
60203                 case 40 /* MinusToken */:
60204                 case 54 /* TildeToken */:
60205                     checkNonNullType(operandType, node.operand);
60206                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60207                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60208                     }
60209                     if (node.operator === 39 /* PlusToken */) {
60210                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60211                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60212                         }
60213                         return numberType;
60214                     }
60215                     return getUnaryResultType(operandType);
60216                 case 53 /* ExclamationToken */:
60217                     checkTruthinessExpression(node.operand);
60218                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60219                     return facts === 4194304 /* Truthy */ ? falseType :
60220                         facts === 8388608 /* Falsy */ ? trueType :
60221                             booleanType;
60222                 case 45 /* PlusPlusToken */:
60223                 case 46 /* MinusMinusToken */:
60224                     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);
60225                     if (ok) {
60226                         // run check only if former checks succeeded to avoid reporting cascading errors
60227                         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);
60228                     }
60229                     return getUnaryResultType(operandType);
60230             }
60231             return errorType;
60232         }
60233         function checkPostfixUnaryExpression(node) {
60234             var operandType = checkExpression(node.operand);
60235             if (operandType === silentNeverType) {
60236                 return silentNeverType;
60237             }
60238             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);
60239             if (ok) {
60240                 // run check only if former checks succeeded to avoid reporting cascading errors
60241                 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);
60242             }
60243             return getUnaryResultType(operandType);
60244         }
60245         function getUnaryResultType(operandType) {
60246             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60247                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60248                     ? numberOrBigIntType
60249                     : bigintType;
60250             }
60251             // If it's not a bigint type, implicit coercion will result in a number
60252             return numberType;
60253         }
60254         // Return true if type might be of the given kind. A union or intersection type might be of a given
60255         // kind if at least one constituent type is of the given kind.
60256         function maybeTypeOfKind(type, kind) {
60257             if (type.flags & kind) {
60258                 return true;
60259             }
60260             if (type.flags & 3145728 /* UnionOrIntersection */) {
60261                 var types = type.types;
60262                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60263                     var t = types_19[_i];
60264                     if (maybeTypeOfKind(t, kind)) {
60265                         return true;
60266                     }
60267                 }
60268             }
60269             return false;
60270         }
60271         function isTypeAssignableToKind(source, kind, strict) {
60272             if (source.flags & kind) {
60273                 return true;
60274             }
60275             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60276                 return false;
60277             }
60278             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60279                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60280                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60281                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60282                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60283                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60284                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60285                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60286                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60287                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60288         }
60289         function allTypesAssignableToKind(source, kind, strict) {
60290             return source.flags & 1048576 /* Union */ ?
60291                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60292                 isTypeAssignableToKind(source, kind, strict);
60293         }
60294         function isConstEnumObjectType(type) {
60295             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60296         }
60297         function isConstEnumSymbol(symbol) {
60298             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60299         }
60300         function checkInstanceOfExpression(left, right, leftType, rightType) {
60301             if (leftType === silentNeverType || rightType === silentNeverType) {
60302                 return silentNeverType;
60303             }
60304             // TypeScript 1.0 spec (April 2014): 4.15.4
60305             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60306             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60307             // The result is always of the Boolean primitive type.
60308             // NOTE: do not raise error if leftType is unknown as related error was already reported
60309             if (!isTypeAny(leftType) &&
60310                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60311                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60312             }
60313             // NOTE: do not raise error if right is unknown as related error was already reported
60314             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60315                 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);
60316             }
60317             return booleanType;
60318         }
60319         function checkInExpression(left, right, leftType, rightType) {
60320             if (leftType === silentNeverType || rightType === silentNeverType) {
60321                 return silentNeverType;
60322             }
60323             leftType = checkNonNullType(leftType, left);
60324             rightType = checkNonNullType(rightType, right);
60325             // TypeScript 1.0 spec (April 2014): 4.15.5
60326             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60327             // and the right operand to be of type Any, an object type, or a type parameter type.
60328             // The result is always of the Boolean primitive type.
60329             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60330                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60331             }
60332             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60333                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60334             }
60335             return booleanType;
60336         }
60337         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60338             var properties = node.properties;
60339             if (strictNullChecks && properties.length === 0) {
60340                 return checkNonNullType(sourceType, node);
60341             }
60342             for (var i = 0; i < properties.length; i++) {
60343                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60344             }
60345             return sourceType;
60346         }
60347         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60348         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60349             if (rightIsThis === void 0) { rightIsThis = false; }
60350             var properties = node.properties;
60351             var property = properties[propertyIndex];
60352             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60353                 var name = property.name;
60354                 var exprType = getLiteralTypeFromPropertyName(name);
60355                 if (isTypeUsableAsPropertyName(exprType)) {
60356                     var text = getPropertyNameFromType(exprType);
60357                     var prop = getPropertyOfType(objectLiteralType, text);
60358                     if (prop) {
60359                         markPropertyAsReferenced(prop, property, rightIsThis);
60360                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60361                     }
60362                 }
60363                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60364                 var type = getFlowTypeOfDestructuring(property, elementType);
60365                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60366             }
60367             else if (property.kind === 283 /* SpreadAssignment */) {
60368                 if (propertyIndex < properties.length - 1) {
60369                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60370                 }
60371                 else {
60372                     if (languageVersion < 99 /* ESNext */) {
60373                         checkExternalEmitHelpers(property, 4 /* Rest */);
60374                     }
60375                     var nonRestNames = [];
60376                     if (allProperties) {
60377                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60378                             var otherProperty = allProperties_1[_i];
60379                             if (!ts.isSpreadAssignment(otherProperty)) {
60380                                 nonRestNames.push(otherProperty.name);
60381                             }
60382                         }
60383                     }
60384                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60385                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60386                     return checkDestructuringAssignment(property.expression, type);
60387                 }
60388             }
60389             else {
60390                 error(property, ts.Diagnostics.Property_assignment_expected);
60391             }
60392         }
60393         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60394             var elements = node.elements;
60395             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60396                 checkExternalEmitHelpers(node, 512 /* Read */);
60397             }
60398             // This elementType will be used if the specific property corresponding to this index is not
60399             // present (aka the tuple element property). This call also checks that the parentType is in
60400             // fact an iterable or array (depending on target language).
60401             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60402             for (var i = 0; i < elements.length; i++) {
60403                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60404             }
60405             return sourceType;
60406         }
60407         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60408             var elements = node.elements;
60409             var element = elements[elementIndex];
60410             if (element.kind !== 215 /* OmittedExpression */) {
60411                 if (element.kind !== 213 /* SpreadElement */) {
60412                     var indexType = getLiteralType(elementIndex);
60413                     if (isArrayLikeType(sourceType)) {
60414                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60415                         // when the element is a SyntaxKind.ElementAccessExpression.
60416                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60417                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60418                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60419                         var type = getFlowTypeOfDestructuring(element, assignedType);
60420                         return checkDestructuringAssignment(element, type, checkMode);
60421                     }
60422                     return checkDestructuringAssignment(element, elementType, checkMode);
60423                 }
60424                 if (elementIndex < elements.length - 1) {
60425                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60426                 }
60427                 else {
60428                     var restExpression = element.expression;
60429                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60430                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60431                     }
60432                     else {
60433                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60434                         var type = everyType(sourceType, isTupleType) ?
60435                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60436                             createArrayType(elementType);
60437                         return checkDestructuringAssignment(restExpression, type, checkMode);
60438                     }
60439                 }
60440             }
60441             return undefined;
60442         }
60443         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60444             var target;
60445             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60446                 var prop = exprOrAssignment;
60447                 if (prop.objectAssignmentInitializer) {
60448                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60449                     // undefined from the final type.
60450                     if (strictNullChecks &&
60451                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60452                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60453                     }
60454                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60455                 }
60456                 target = exprOrAssignment.name;
60457             }
60458             else {
60459                 target = exprOrAssignment;
60460             }
60461             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60462                 checkBinaryExpression(target, checkMode);
60463                 target = target.left;
60464             }
60465             if (target.kind === 193 /* ObjectLiteralExpression */) {
60466                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60467             }
60468             if (target.kind === 192 /* ArrayLiteralExpression */) {
60469                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60470             }
60471             return checkReferenceAssignment(target, sourceType, checkMode);
60472         }
60473         function checkReferenceAssignment(target, sourceType, checkMode) {
60474             var targetType = checkExpression(target, checkMode);
60475             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60476                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60477                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60478             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60479                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60480                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60481             if (checkReferenceExpression(target, error, optionalError)) {
60482                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60483             }
60484             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60485                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60486             }
60487             return sourceType;
60488         }
60489         /**
60490          * This is a *shallow* check: An expression is side-effect-free if the
60491          * evaluation of the expression *itself* cannot produce side effects.
60492          * For example, x++ / 3 is side-effect free because the / operator
60493          * does not have side effects.
60494          * The intent is to "smell test" an expression for correctness in positions where
60495          * its value is discarded (e.g. the left side of the comma operator).
60496          */
60497         function isSideEffectFree(node) {
60498             node = ts.skipParentheses(node);
60499             switch (node.kind) {
60500                 case 75 /* Identifier */:
60501                 case 10 /* StringLiteral */:
60502                 case 13 /* RegularExpressionLiteral */:
60503                 case 198 /* TaggedTemplateExpression */:
60504                 case 211 /* TemplateExpression */:
60505                 case 14 /* NoSubstitutionTemplateLiteral */:
60506                 case 8 /* NumericLiteral */:
60507                 case 9 /* BigIntLiteral */:
60508                 case 106 /* TrueKeyword */:
60509                 case 91 /* FalseKeyword */:
60510                 case 100 /* NullKeyword */:
60511                 case 146 /* UndefinedKeyword */:
60512                 case 201 /* FunctionExpression */:
60513                 case 214 /* ClassExpression */:
60514                 case 202 /* ArrowFunction */:
60515                 case 192 /* ArrayLiteralExpression */:
60516                 case 193 /* ObjectLiteralExpression */:
60517                 case 204 /* TypeOfExpression */:
60518                 case 218 /* NonNullExpression */:
60519                 case 267 /* JsxSelfClosingElement */:
60520                 case 266 /* JsxElement */:
60521                     return true;
60522                 case 210 /* ConditionalExpression */:
60523                     return isSideEffectFree(node.whenTrue) &&
60524                         isSideEffectFree(node.whenFalse);
60525                 case 209 /* BinaryExpression */:
60526                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60527                         return false;
60528                     }
60529                     return isSideEffectFree(node.left) &&
60530                         isSideEffectFree(node.right);
60531                 case 207 /* PrefixUnaryExpression */:
60532                 case 208 /* PostfixUnaryExpression */:
60533                     // Unary operators ~, !, +, and - have no side effects.
60534                     // The rest do.
60535                     switch (node.operator) {
60536                         case 53 /* ExclamationToken */:
60537                         case 39 /* PlusToken */:
60538                         case 40 /* MinusToken */:
60539                         case 54 /* TildeToken */:
60540                             return true;
60541                     }
60542                     return false;
60543                 // Some forms listed here for clarity
60544                 case 205 /* VoidExpression */: // Explicit opt-out
60545                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60546                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60547                 default:
60548                     return false;
60549             }
60550         }
60551         function isTypeEqualityComparableTo(source, target) {
60552             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60553         }
60554         var CheckBinaryExpressionState;
60555         (function (CheckBinaryExpressionState) {
60556             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60557             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60558             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60559         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60560         function checkBinaryExpression(node, checkMode) {
60561             var workStacks = {
60562                 expr: [node],
60563                 state: [0 /* MaybeCheckLeft */],
60564                 leftType: [undefined]
60565             };
60566             var stackIndex = 0;
60567             var lastResult;
60568             while (stackIndex >= 0) {
60569                 node = workStacks.expr[stackIndex];
60570                 switch (workStacks.state[stackIndex]) {
60571                     case 0 /* MaybeCheckLeft */: {
60572                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60573                             finishInvocation(checkExpression(node.right, checkMode));
60574                             break;
60575                         }
60576                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60577                         var operator = node.operatorToken.kind;
60578                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60579                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60580                             break;
60581                         }
60582                         advanceState(1 /* CheckRight */);
60583                         maybeCheckExpression(node.left);
60584                         break;
60585                     }
60586                     case 1 /* CheckRight */: {
60587                         var leftType = lastResult;
60588                         workStacks.leftType[stackIndex] = leftType;
60589                         var operator = node.operatorToken.kind;
60590                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60591                             checkTruthinessOfType(leftType, node.left);
60592                         }
60593                         advanceState(2 /* FinishCheck */);
60594                         maybeCheckExpression(node.right);
60595                         break;
60596                     }
60597                     case 2 /* FinishCheck */: {
60598                         var leftType = workStacks.leftType[stackIndex];
60599                         var rightType = lastResult;
60600                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60601                         break;
60602                     }
60603                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60604                 }
60605             }
60606             return lastResult;
60607             function finishInvocation(result) {
60608                 lastResult = result;
60609                 stackIndex--;
60610             }
60611             /**
60612              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60613              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60614              */
60615             function advanceState(nextState) {
60616                 workStacks.state[stackIndex] = nextState;
60617             }
60618             function maybeCheckExpression(node) {
60619                 if (ts.isBinaryExpression(node)) {
60620                     stackIndex++;
60621                     workStacks.expr[stackIndex] = node;
60622                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60623                     workStacks.leftType[stackIndex] = undefined;
60624                 }
60625                 else {
60626                     lastResult = checkExpression(node, checkMode);
60627                 }
60628             }
60629         }
60630         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60631             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60632             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60633                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60634                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60635                 }
60636                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60637                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60638                 }
60639             }
60640         }
60641         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60642         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60643         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60644             var operator = operatorToken.kind;
60645             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60646                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60647             }
60648             var leftType;
60649             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60650                 leftType = checkTruthinessExpression(left, checkMode);
60651             }
60652             else {
60653                 leftType = checkExpression(left, checkMode);
60654             }
60655             var rightType = checkExpression(right, checkMode);
60656             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60657         }
60658         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60659             var operator = operatorToken.kind;
60660             switch (operator) {
60661                 case 41 /* AsteriskToken */:
60662                 case 42 /* AsteriskAsteriskToken */:
60663                 case 65 /* AsteriskEqualsToken */:
60664                 case 66 /* AsteriskAsteriskEqualsToken */:
60665                 case 43 /* SlashToken */:
60666                 case 67 /* SlashEqualsToken */:
60667                 case 44 /* PercentToken */:
60668                 case 68 /* PercentEqualsToken */:
60669                 case 40 /* MinusToken */:
60670                 case 64 /* MinusEqualsToken */:
60671                 case 47 /* LessThanLessThanToken */:
60672                 case 69 /* LessThanLessThanEqualsToken */:
60673                 case 48 /* GreaterThanGreaterThanToken */:
60674                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60675                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60676                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60677                 case 51 /* BarToken */:
60678                 case 73 /* BarEqualsToken */:
60679                 case 52 /* CaretToken */:
60680                 case 74 /* CaretEqualsToken */:
60681                 case 50 /* AmpersandToken */:
60682                 case 72 /* AmpersandEqualsToken */:
60683                     if (leftType === silentNeverType || rightType === silentNeverType) {
60684                         return silentNeverType;
60685                     }
60686                     leftType = checkNonNullType(leftType, left);
60687                     rightType = checkNonNullType(rightType, right);
60688                     var suggestedOperator = void 0;
60689                     // if a user tries to apply a bitwise operator to 2 boolean operands
60690                     // try and return them a helpful suggestion
60691                     if ((leftType.flags & 528 /* BooleanLike */) &&
60692                         (rightType.flags & 528 /* BooleanLike */) &&
60693                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60694                         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));
60695                         return numberType;
60696                     }
60697                     else {
60698                         // otherwise just check each operand separately and report errors as normal
60699                         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);
60700                         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);
60701                         var resultType_1;
60702                         // If both are any or unknown, allow operation; assume it will resolve to number
60703                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60704                             // Or, if neither could be bigint, implicit coercion results in a number result
60705                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60706                             resultType_1 = numberType;
60707                         }
60708                         // At least one is assignable to bigint, so check that both are
60709                         else if (bothAreBigIntLike(leftType, rightType)) {
60710                             switch (operator) {
60711                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60712                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60713                                     reportOperatorError();
60714                             }
60715                             resultType_1 = bigintType;
60716                         }
60717                         // Exactly one of leftType/rightType is assignable to bigint
60718                         else {
60719                             reportOperatorError(bothAreBigIntLike);
60720                             resultType_1 = errorType;
60721                         }
60722                         if (leftOk && rightOk) {
60723                             checkAssignmentOperator(resultType_1);
60724                         }
60725                         return resultType_1;
60726                     }
60727                 case 39 /* PlusToken */:
60728                 case 63 /* PlusEqualsToken */:
60729                     if (leftType === silentNeverType || rightType === silentNeverType) {
60730                         return silentNeverType;
60731                     }
60732                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60733                         leftType = checkNonNullType(leftType, left);
60734                         rightType = checkNonNullType(rightType, right);
60735                     }
60736                     var resultType = void 0;
60737                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60738                         // Operands of an enum type are treated as having the primitive type Number.
60739                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60740                         resultType = numberType;
60741                     }
60742                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60743                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60744                         resultType = bigintType;
60745                     }
60746                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60747                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60748                         resultType = stringType;
60749                     }
60750                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60751                         // Otherwise, the result is of type Any.
60752                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60753                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60754                     }
60755                     // Symbols are not allowed at all in arithmetic expressions
60756                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60757                         return resultType;
60758                     }
60759                     if (!resultType) {
60760                         // Types that have a reasonably good chance of being a valid operand type.
60761                         // If both types have an awaited type of one of these, we'll assume the user
60762                         // might be missing an await without doing an exhaustive check that inserting
60763                         // await(s) will actually be a completely valid binary expression.
60764                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60765                         reportOperatorError(function (left, right) {
60766                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60767                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60768                         });
60769                         return anyType;
60770                     }
60771                     if (operator === 63 /* PlusEqualsToken */) {
60772                         checkAssignmentOperator(resultType);
60773                     }
60774                     return resultType;
60775                 case 29 /* LessThanToken */:
60776                 case 31 /* GreaterThanToken */:
60777                 case 32 /* LessThanEqualsToken */:
60778                 case 33 /* GreaterThanEqualsToken */:
60779                     if (checkForDisallowedESSymbolOperand(operator)) {
60780                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60781                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60782                         reportOperatorErrorUnless(function (left, right) {
60783                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60784                         });
60785                     }
60786                     return booleanType;
60787                 case 34 /* EqualsEqualsToken */:
60788                 case 35 /* ExclamationEqualsToken */:
60789                 case 36 /* EqualsEqualsEqualsToken */:
60790                 case 37 /* ExclamationEqualsEqualsToken */:
60791                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60792                     return booleanType;
60793                 case 98 /* InstanceOfKeyword */:
60794                     return checkInstanceOfExpression(left, right, leftType, rightType);
60795                 case 97 /* InKeyword */:
60796                     return checkInExpression(left, right, leftType, rightType);
60797                 case 55 /* AmpersandAmpersandToken */:
60798                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60799                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60800                         leftType;
60801                 case 56 /* BarBarToken */:
60802                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60803                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60804                         leftType;
60805                 case 60 /* QuestionQuestionToken */:
60806                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60807                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60808                         leftType;
60809                 case 62 /* EqualsToken */:
60810                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60811                     checkAssignmentDeclaration(declKind, rightType);
60812                     if (isAssignmentDeclaration(declKind)) {
60813                         if (!(rightType.flags & 524288 /* Object */) ||
60814                             declKind !== 2 /* ModuleExports */ &&
60815                                 declKind !== 6 /* Prototype */ &&
60816                                 !isEmptyObjectType(rightType) &&
60817                                 !isFunctionObjectType(rightType) &&
60818                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
60819                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
60820                             checkAssignmentOperator(rightType);
60821                         }
60822                         return leftType;
60823                     }
60824                     else {
60825                         checkAssignmentOperator(rightType);
60826                         return getRegularTypeOfObjectLiteral(rightType);
60827                     }
60828                 case 27 /* CommaToken */:
60829                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
60830                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
60831                     }
60832                     return rightType;
60833                 default:
60834                     return ts.Debug.fail();
60835             }
60836             function bothAreBigIntLike(left, right) {
60837                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
60838             }
60839             function checkAssignmentDeclaration(kind, rightType) {
60840                 if (kind === 2 /* ModuleExports */) {
60841                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
60842                         var prop = _a[_i];
60843                         var propType = getTypeOfSymbol(prop);
60844                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
60845                             var name = prop.escapedName;
60846                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
60847                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
60848                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
60849                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
60850                             }
60851                         }
60852                     }
60853                 }
60854             }
60855             function isEvalNode(node) {
60856                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
60857             }
60858             // Return true if there was no error, false if there was an error.
60859             function checkForDisallowedESSymbolOperand(operator) {
60860                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
60861                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
60862                         undefined;
60863                 if (offendingSymbolOperand) {
60864                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
60865                     return false;
60866                 }
60867                 return true;
60868             }
60869             function getSuggestedBooleanOperator(operator) {
60870                 switch (operator) {
60871                     case 51 /* BarToken */:
60872                     case 73 /* BarEqualsToken */:
60873                         return 56 /* BarBarToken */;
60874                     case 52 /* CaretToken */:
60875                     case 74 /* CaretEqualsToken */:
60876                         return 37 /* ExclamationEqualsEqualsToken */;
60877                     case 50 /* AmpersandToken */:
60878                     case 72 /* AmpersandEqualsToken */:
60879                         return 55 /* AmpersandAmpersandToken */;
60880                     default:
60881                         return undefined;
60882                 }
60883             }
60884             function checkAssignmentOperator(valueType) {
60885                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
60886                     // TypeScript 1.0 spec (April 2014): 4.17
60887                     // An assignment of the form
60888                     //    VarExpr = ValueExpr
60889                     // requires VarExpr to be classified as a reference
60890                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
60891                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
60892                     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)
60893                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
60894                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
60895                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
60896                     }
60897                 }
60898             }
60899             function isAssignmentDeclaration(kind) {
60900                 switch (kind) {
60901                     case 2 /* ModuleExports */:
60902                         return true;
60903                     case 1 /* ExportsProperty */:
60904                     case 5 /* Property */:
60905                     case 6 /* Prototype */:
60906                     case 3 /* PrototypeProperty */:
60907                     case 4 /* ThisProperty */:
60908                         var symbol = getSymbolOfNode(left);
60909                         var init = ts.getAssignedExpandoInitializer(right);
60910                         return init && ts.isObjectLiteralExpression(init) &&
60911                             symbol && ts.hasEntries(symbol.exports);
60912                     default:
60913                         return false;
60914                 }
60915             }
60916             /**
60917              * Returns true if an error is reported
60918              */
60919             function reportOperatorErrorUnless(typesAreCompatible) {
60920                 if (!typesAreCompatible(leftType, rightType)) {
60921                     reportOperatorError(typesAreCompatible);
60922                     return true;
60923                 }
60924                 return false;
60925             }
60926             function reportOperatorError(isRelated) {
60927                 var _a;
60928                 var wouldWorkWithAwait = false;
60929                 var errNode = errorNode || operatorToken;
60930                 if (isRelated) {
60931                     var awaitedLeftType = getAwaitedType(leftType);
60932                     var awaitedRightType = getAwaitedType(rightType);
60933                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
60934                         && !!(awaitedLeftType && awaitedRightType)
60935                         && isRelated(awaitedLeftType, awaitedRightType);
60936                 }
60937                 var effectiveLeft = leftType;
60938                 var effectiveRight = rightType;
60939                 if (!wouldWorkWithAwait && isRelated) {
60940                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
60941                 }
60942                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
60943                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
60944                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
60945                 }
60946             }
60947             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
60948                 var typeName;
60949                 switch (operatorToken.kind) {
60950                     case 36 /* EqualsEqualsEqualsToken */:
60951                     case 34 /* EqualsEqualsToken */:
60952                         typeName = "false";
60953                         break;
60954                     case 37 /* ExclamationEqualsEqualsToken */:
60955                     case 35 /* ExclamationEqualsToken */:
60956                         typeName = "true";
60957                 }
60958                 if (typeName) {
60959                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
60960                 }
60961                 return undefined;
60962             }
60963         }
60964         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
60965             var effectiveLeft = leftType;
60966             var effectiveRight = rightType;
60967             var leftBase = getBaseTypeOfLiteralType(leftType);
60968             var rightBase = getBaseTypeOfLiteralType(rightType);
60969             if (!isRelated(leftBase, rightBase)) {
60970                 effectiveLeft = leftBase;
60971                 effectiveRight = rightBase;
60972             }
60973             return [effectiveLeft, effectiveRight];
60974         }
60975         function checkYieldExpression(node) {
60976             // Grammar checking
60977             if (produceDiagnostics) {
60978                 if (!(node.flags & 8192 /* YieldContext */)) {
60979                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
60980                 }
60981                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60982                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
60983                 }
60984             }
60985             var func = ts.getContainingFunction(node);
60986             if (!func)
60987                 return anyType;
60988             var functionFlags = ts.getFunctionFlags(func);
60989             if (!(functionFlags & 1 /* Generator */)) {
60990                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
60991                 return anyType;
60992             }
60993             var isAsync = (functionFlags & 2 /* Async */) !== 0;
60994             if (node.asteriskToken) {
60995                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
60996                 // and __asyncValues helpers
60997                 if (isAsync && languageVersion < 99 /* ESNext */) {
60998                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
60999                 }
61000                 // Generator functions prior to ES2015 require the __values helper
61001                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61002                     checkExternalEmitHelpers(node, 256 /* Values */);
61003                 }
61004             }
61005             // There is no point in doing an assignability check if the function
61006             // has no explicit return type because the return type is directly computed
61007             // from the yield expressions.
61008             var returnType = getReturnTypeFromAnnotation(func);
61009             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61010             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61011             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61012             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61013             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61014             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61015             if (returnType && yieldedType) {
61016                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61017             }
61018             if (node.asteriskToken) {
61019                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61020                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61021                     || anyType;
61022             }
61023             else if (returnType) {
61024                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61025                     || anyType;
61026             }
61027             return getContextualIterationType(2 /* Next */, func) || anyType;
61028         }
61029         function checkConditionalExpression(node, checkMode) {
61030             var type = checkTruthinessExpression(node.condition);
61031             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61032             var type1 = checkExpression(node.whenTrue, checkMode);
61033             var type2 = checkExpression(node.whenFalse, checkMode);
61034             return getUnionType([type1, type2], 2 /* Subtype */);
61035         }
61036         function checkTemplateExpression(node) {
61037             // We just want to check each expressions, but we are unconcerned with
61038             // the type of each expression, as any value may be coerced into a string.
61039             // It is worth asking whether this is what we really want though.
61040             // A place where we actually *are* concerned with the expressions' types are
61041             // in tagged templates.
61042             ts.forEach(node.templateSpans, function (templateSpan) {
61043                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61044                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61045                 }
61046             });
61047             return stringType;
61048         }
61049         function getContextNode(node) {
61050             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61051                 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)
61052             }
61053             return node;
61054         }
61055         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61056             var context = getContextNode(node);
61057             var saveContextualType = context.contextualType;
61058             var saveInferenceContext = context.inferenceContext;
61059             try {
61060                 context.contextualType = contextualType;
61061                 context.inferenceContext = inferenceContext;
61062                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61063                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61064                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61065                 // here would be to not mark contextually typed literals as fresh in the first place.
61066                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61067                     getRegularTypeOfLiteralType(type) : type;
61068                 return result;
61069             }
61070             finally {
61071                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61072                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61073                 // may hold onto the checker that created it.
61074                 context.contextualType = saveContextualType;
61075                 context.inferenceContext = saveInferenceContext;
61076             }
61077         }
61078         function checkExpressionCached(node, checkMode) {
61079             var links = getNodeLinks(node);
61080             if (!links.resolvedType) {
61081                 if (checkMode && checkMode !== 0 /* Normal */) {
61082                     return checkExpression(node, checkMode);
61083                 }
61084                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61085                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61086                 // to the top of the stack ensures all transient types are computed from a known point.
61087                 var saveFlowLoopStart = flowLoopStart;
61088                 var saveFlowTypeCache = flowTypeCache;
61089                 flowLoopStart = flowLoopCount;
61090                 flowTypeCache = undefined;
61091                 links.resolvedType = checkExpression(node, checkMode);
61092                 flowTypeCache = saveFlowTypeCache;
61093                 flowLoopStart = saveFlowLoopStart;
61094             }
61095             return links.resolvedType;
61096         }
61097         function isTypeAssertion(node) {
61098             node = ts.skipParentheses(node);
61099             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61100         }
61101         function checkDeclarationInitializer(declaration, contextualType) {
61102             var initializer = ts.getEffectiveInitializer(declaration);
61103             var type = getQuickTypeOfExpression(initializer) ||
61104                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61105             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61106                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61107                 padTupleType(type, declaration.name) : type;
61108         }
61109         function padTupleType(type, pattern) {
61110             var patternElements = pattern.elements;
61111             var arity = getTypeReferenceArity(type);
61112             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61113             for (var i = arity; i < patternElements.length; i++) {
61114                 var e = patternElements[i];
61115                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61116                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61117                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61118                         reportImplicitAny(e, anyType);
61119                     }
61120                 }
61121             }
61122             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61123         }
61124         function widenTypeInferredFromInitializer(declaration, type) {
61125             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61126             if (ts.isInJSFile(declaration)) {
61127                 if (widened.flags & 98304 /* Nullable */) {
61128                     reportImplicitAny(declaration, anyType);
61129                     return anyType;
61130                 }
61131                 else if (isEmptyArrayLiteralType(widened)) {
61132                     reportImplicitAny(declaration, anyArrayType);
61133                     return anyArrayType;
61134                 }
61135             }
61136             return widened;
61137         }
61138         function isLiteralOfContextualType(candidateType, contextualType) {
61139             if (contextualType) {
61140                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61141                     var types = contextualType.types;
61142                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61143                 }
61144                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61145                     // If the contextual type is a type variable constrained to a primitive type, consider
61146                     // this a literal context for literals of that primitive type. For example, given a
61147                     // type parameter 'T extends string', infer string literal types for T.
61148                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61149                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61150                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61151                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61152                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61153                         isLiteralOfContextualType(candidateType, constraint);
61154                 }
61155                 // If the contextual type is a literal of a particular primitive type, we consider this a
61156                 // literal context for all literals of that primitive type.
61157                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61158                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61159                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61160                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61161                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61162             }
61163             return false;
61164         }
61165         function isConstContext(node) {
61166             var parent = node.parent;
61167             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61168                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61169                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61170         }
61171         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61172             var type = checkExpression(node, checkMode, forceTuple);
61173             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61174                 isTypeAssertion(node) ? type :
61175                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61176         }
61177         function checkPropertyAssignment(node, checkMode) {
61178             // Do not use hasDynamicName here, because that returns false for well known symbols.
61179             // We want to perform checkComputedPropertyName for all computed properties, including
61180             // well known symbols.
61181             if (node.name.kind === 154 /* ComputedPropertyName */) {
61182                 checkComputedPropertyName(node.name);
61183             }
61184             return checkExpressionForMutableLocation(node.initializer, checkMode);
61185         }
61186         function checkObjectLiteralMethod(node, checkMode) {
61187             // Grammar checking
61188             checkGrammarMethod(node);
61189             // Do not use hasDynamicName here, because that returns false for well known symbols.
61190             // We want to perform checkComputedPropertyName for all computed properties, including
61191             // well known symbols.
61192             if (node.name.kind === 154 /* ComputedPropertyName */) {
61193                 checkComputedPropertyName(node.name);
61194             }
61195             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61196             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61197         }
61198         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61199             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61200                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61201                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61202                 var signature = callSignature || constructSignature;
61203                 if (signature && signature.typeParameters) {
61204                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61205                     if (contextualType) {
61206                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61207                         if (contextualSignature && !contextualSignature.typeParameters) {
61208                             if (checkMode & 8 /* SkipGenericFunctions */) {
61209                                 skippedGenericFunction(node, checkMode);
61210                                 return anyFunctionType;
61211                             }
61212                             var context = getInferenceContext(node);
61213                             // We have an expression that is an argument of a generic function for which we are performing
61214                             // type argument inference. The expression is of a function type with a single generic call
61215                             // signature and a contextual function type with a single non-generic call signature. Now check
61216                             // if the outer function returns a function type with a single non-generic call signature and
61217                             // if some of the outer function type parameters have no inferences so far. If so, we can
61218                             // potentially add inferred type parameters to the outer function return type.
61219                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61220                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61221                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61222                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61223                                 // renaming the type parameters to ensure they have unique names.
61224                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61225                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61226                                 // Infer from the parameters of the instantiated signature to the parameters of the
61227                                 // contextual signature starting with an empty set of inference candidates.
61228                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61229                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61230                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61231                                 });
61232                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61233                                     // We have inference candidates, indicating that one or more type parameters are referenced
61234                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61235                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61236                                         inferTypes(inferences_3, source, target);
61237                                     });
61238                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61239                                     // we adopt the new inference candidates and add the type parameters of the expression type
61240                                     // to the set of inferred type parameters for the outer function return type.
61241                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61242                                         mergeInferences(context.inferences, inferences_3);
61243                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61244                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61245                                     }
61246                                 }
61247                             }
61248                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61249                         }
61250                     }
61251                 }
61252             }
61253             return type;
61254         }
61255         function skippedGenericFunction(node, checkMode) {
61256             if (checkMode & 2 /* Inferential */) {
61257                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61258                 // indicate this has occurred such that we know a second pass of inference is be needed.
61259                 var context = getInferenceContext(node);
61260                 context.flags |= 4 /* SkippedGenericFunction */;
61261             }
61262         }
61263         function hasInferenceCandidates(info) {
61264             return !!(info.candidates || info.contraCandidates);
61265         }
61266         function hasOverlappingInferences(a, b) {
61267             for (var i = 0; i < a.length; i++) {
61268                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61269                     return true;
61270                 }
61271             }
61272             return false;
61273         }
61274         function mergeInferences(target, source) {
61275             for (var i = 0; i < target.length; i++) {
61276                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61277                     target[i] = source[i];
61278                 }
61279             }
61280         }
61281         function getUniqueTypeParameters(context, typeParameters) {
61282             var result = [];
61283             var oldTypeParameters;
61284             var newTypeParameters;
61285             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61286                 var tp = typeParameters_2[_i];
61287                 var name = tp.symbol.escapedName;
61288                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61289                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61290                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61291                     var newTypeParameter = createTypeParameter(symbol);
61292                     newTypeParameter.target = tp;
61293                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61294                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61295                     result.push(newTypeParameter);
61296                 }
61297                 else {
61298                     result.push(tp);
61299                 }
61300             }
61301             if (newTypeParameters) {
61302                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61303                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61304                     var tp = newTypeParameters_1[_a];
61305                     tp.mapper = mapper;
61306                 }
61307             }
61308             return result;
61309         }
61310         function hasTypeParameterByName(typeParameters, name) {
61311             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61312         }
61313         function getUniqueTypeParameterName(typeParameters, baseName) {
61314             var len = baseName.length;
61315             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61316                 len--;
61317             var s = baseName.slice(0, len);
61318             for (var index = 1; true; index++) {
61319                 var augmentedName = (s + index);
61320                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61321                     return augmentedName;
61322                 }
61323             }
61324         }
61325         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61326             var signature = getSingleCallSignature(funcType);
61327             if (signature && !signature.typeParameters) {
61328                 return getReturnTypeOfSignature(signature);
61329             }
61330         }
61331         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61332             var funcType = checkExpression(expr.expression);
61333             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61334             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61335             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61336         }
61337         /**
61338          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61339          * with computing the type and may not fully check all contained sub-expressions for errors.
61340          */
61341         function getTypeOfExpression(node) {
61342             // Don't bother caching types that require no flow analysis and are quick to compute.
61343             var quickType = getQuickTypeOfExpression(node);
61344             if (quickType) {
61345                 return quickType;
61346             }
61347             // If a type has been cached for the node, return it.
61348             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61349                 var cachedType = flowTypeCache[getNodeId(node)];
61350                 if (cachedType) {
61351                     return cachedType;
61352                 }
61353             }
61354             var startInvocationCount = flowInvocationCount;
61355             var type = checkExpression(node);
61356             // If control flow analysis was required to determine the type, it is worth caching.
61357             if (flowInvocationCount !== startInvocationCount) {
61358                 var cache = flowTypeCache || (flowTypeCache = []);
61359                 cache[getNodeId(node)] = type;
61360                 node.flags |= 67108864 /* TypeCached */;
61361             }
61362             return type;
61363         }
61364         function getQuickTypeOfExpression(node) {
61365             var expr = ts.skipParentheses(node);
61366             // Optimize for the common case of a call to a function with a single non-generic call
61367             // signature where we can just fetch the return type without checking the arguments.
61368             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61369                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61370                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61371                 if (type) {
61372                     return type;
61373                 }
61374             }
61375             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61376                 return getTypeFromTypeNode(expr.type);
61377             }
61378             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61379                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61380                 return checkExpression(node);
61381             }
61382             return undefined;
61383         }
61384         /**
61385          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61386          * with computing the type and may not fully check all contained sub-expressions for errors.
61387          * It is intended for uses where you know there is no contextual type,
61388          * and requesting the contextual type might cause a circularity or other bad behaviour.
61389          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61390          */
61391         function getContextFreeTypeOfExpression(node) {
61392             var links = getNodeLinks(node);
61393             if (links.contextFreeType) {
61394                 return links.contextFreeType;
61395             }
61396             var saveContextualType = node.contextualType;
61397             node.contextualType = anyType;
61398             try {
61399                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61400                 return type;
61401             }
61402             finally {
61403                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61404                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61405                 // may hold onto the checker that created it.
61406                 node.contextualType = saveContextualType;
61407             }
61408         }
61409         function checkExpression(node, checkMode, forceTuple) {
61410             var saveCurrentNode = currentNode;
61411             currentNode = node;
61412             instantiationCount = 0;
61413             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61414             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61415             if (isConstEnumObjectType(type)) {
61416                 checkConstEnumAccess(node, type);
61417             }
61418             currentNode = saveCurrentNode;
61419             return type;
61420         }
61421         function checkConstEnumAccess(node, type) {
61422             // enum object type for const enums are only permitted in:
61423             // - 'left' in property access
61424             // - 'object' in indexed access
61425             // - target in rhs of import statement
61426             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61427                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61428                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61429                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61430                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61431             if (!ok) {
61432                 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);
61433             }
61434             if (compilerOptions.isolatedModules) {
61435                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61436                 var constEnumDeclaration = type.symbol.valueDeclaration;
61437                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61438                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61439                 }
61440             }
61441         }
61442         function checkParenthesizedExpression(node, checkMode) {
61443             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61444             if (tag) {
61445                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61446             }
61447             return checkExpression(node.expression, checkMode);
61448         }
61449         function checkExpressionWorker(node, checkMode, forceTuple) {
61450             var kind = node.kind;
61451             if (cancellationToken) {
61452                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61453                 // hitting the cancellation token on every node we check.
61454                 switch (kind) {
61455                     case 214 /* ClassExpression */:
61456                     case 201 /* FunctionExpression */:
61457                     case 202 /* ArrowFunction */:
61458                         cancellationToken.throwIfCancellationRequested();
61459                 }
61460             }
61461             switch (kind) {
61462                 case 75 /* Identifier */:
61463                     return checkIdentifier(node);
61464                 case 104 /* ThisKeyword */:
61465                     return checkThisExpression(node);
61466                 case 102 /* SuperKeyword */:
61467                     return checkSuperExpression(node);
61468                 case 100 /* NullKeyword */:
61469                     return nullWideningType;
61470                 case 14 /* NoSubstitutionTemplateLiteral */:
61471                 case 10 /* StringLiteral */:
61472                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61473                 case 8 /* NumericLiteral */:
61474                     checkGrammarNumericLiteral(node);
61475                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61476                 case 9 /* BigIntLiteral */:
61477                     checkGrammarBigIntLiteral(node);
61478                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61479                 case 106 /* TrueKeyword */:
61480                     return trueType;
61481                 case 91 /* FalseKeyword */:
61482                     return falseType;
61483                 case 211 /* TemplateExpression */:
61484                     return checkTemplateExpression(node);
61485                 case 13 /* RegularExpressionLiteral */:
61486                     return globalRegExpType;
61487                 case 192 /* ArrayLiteralExpression */:
61488                     return checkArrayLiteral(node, checkMode, forceTuple);
61489                 case 193 /* ObjectLiteralExpression */:
61490                     return checkObjectLiteral(node, checkMode);
61491                 case 194 /* PropertyAccessExpression */:
61492                     return checkPropertyAccessExpression(node);
61493                 case 153 /* QualifiedName */:
61494                     return checkQualifiedName(node);
61495                 case 195 /* ElementAccessExpression */:
61496                     return checkIndexedAccess(node);
61497                 case 196 /* CallExpression */:
61498                     if (node.expression.kind === 96 /* ImportKeyword */) {
61499                         return checkImportCallExpression(node);
61500                     }
61501                 // falls through
61502                 case 197 /* NewExpression */:
61503                     return checkCallExpression(node, checkMode);
61504                 case 198 /* TaggedTemplateExpression */:
61505                     return checkTaggedTemplateExpression(node);
61506                 case 200 /* ParenthesizedExpression */:
61507                     return checkParenthesizedExpression(node, checkMode);
61508                 case 214 /* ClassExpression */:
61509                     return checkClassExpression(node);
61510                 case 201 /* FunctionExpression */:
61511                 case 202 /* ArrowFunction */:
61512                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61513                 case 204 /* TypeOfExpression */:
61514                     return checkTypeOfExpression(node);
61515                 case 199 /* TypeAssertionExpression */:
61516                 case 217 /* AsExpression */:
61517                     return checkAssertion(node);
61518                 case 218 /* NonNullExpression */:
61519                     return checkNonNullAssertion(node);
61520                 case 219 /* MetaProperty */:
61521                     return checkMetaProperty(node);
61522                 case 203 /* DeleteExpression */:
61523                     return checkDeleteExpression(node);
61524                 case 205 /* VoidExpression */:
61525                     return checkVoidExpression(node);
61526                 case 206 /* AwaitExpression */:
61527                     return checkAwaitExpression(node);
61528                 case 207 /* PrefixUnaryExpression */:
61529                     return checkPrefixUnaryExpression(node);
61530                 case 208 /* PostfixUnaryExpression */:
61531                     return checkPostfixUnaryExpression(node);
61532                 case 209 /* BinaryExpression */:
61533                     return checkBinaryExpression(node, checkMode);
61534                 case 210 /* ConditionalExpression */:
61535                     return checkConditionalExpression(node, checkMode);
61536                 case 213 /* SpreadElement */:
61537                     return checkSpreadExpression(node, checkMode);
61538                 case 215 /* OmittedExpression */:
61539                     return undefinedWideningType;
61540                 case 212 /* YieldExpression */:
61541                     return checkYieldExpression(node);
61542                 case 220 /* SyntheticExpression */:
61543                     return node.type;
61544                 case 276 /* JsxExpression */:
61545                     return checkJsxExpression(node, checkMode);
61546                 case 266 /* JsxElement */:
61547                     return checkJsxElement(node, checkMode);
61548                 case 267 /* JsxSelfClosingElement */:
61549                     return checkJsxSelfClosingElement(node, checkMode);
61550                 case 270 /* JsxFragment */:
61551                     return checkJsxFragment(node);
61552                 case 274 /* JsxAttributes */:
61553                     return checkJsxAttributes(node, checkMode);
61554                 case 268 /* JsxOpeningElement */:
61555                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61556             }
61557             return errorType;
61558         }
61559         // DECLARATION AND STATEMENT TYPE CHECKING
61560         function checkTypeParameter(node) {
61561             // Grammar Checking
61562             if (node.expression) {
61563                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61564             }
61565             checkSourceElement(node.constraint);
61566             checkSourceElement(node.default);
61567             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61568             // Resolve base constraint to reveal circularity errors
61569             getBaseConstraintOfType(typeParameter);
61570             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61571                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61572             }
61573             var constraintType = getConstraintOfTypeParameter(typeParameter);
61574             var defaultType = getDefaultFromTypeParameter(typeParameter);
61575             if (constraintType && defaultType) {
61576                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61577             }
61578             if (produceDiagnostics) {
61579                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61580             }
61581         }
61582         function checkParameter(node) {
61583             // Grammar checking
61584             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61585             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61586             // or if its FunctionBody is strict code(11.1.5).
61587             checkGrammarDecoratorsAndModifiers(node);
61588             checkVariableLikeDeclaration(node);
61589             var func = ts.getContainingFunction(node);
61590             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61591                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61592                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61593                 }
61594                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61595                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61596                 }
61597             }
61598             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61599                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61600             }
61601             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61602                 if (func.parameters.indexOf(node) !== 0) {
61603                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61604                 }
61605                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61606                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61607                 }
61608                 if (func.kind === 202 /* ArrowFunction */) {
61609                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61610                 }
61611                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61612                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61613                 }
61614             }
61615             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61616             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61617             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61618                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61619             }
61620         }
61621         function checkTypePredicate(node) {
61622             var parent = getTypePredicateParent(node);
61623             if (!parent) {
61624                 // The parent must not be valid.
61625                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61626                 return;
61627             }
61628             var signature = getSignatureFromDeclaration(parent);
61629             var typePredicate = getTypePredicateOfSignature(signature);
61630             if (!typePredicate) {
61631                 return;
61632             }
61633             checkSourceElement(node.type);
61634             var parameterName = node.parameterName;
61635             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61636                 getTypeFromThisTypeNode(parameterName);
61637             }
61638             else {
61639                 if (typePredicate.parameterIndex >= 0) {
61640                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61641                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61642                     }
61643                     else {
61644                         if (typePredicate.type) {
61645                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61646                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61647                             /*headMessage*/ undefined, leadingError);
61648                         }
61649                     }
61650                 }
61651                 else if (parameterName) {
61652                     var hasReportedError = false;
61653                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61654                         var name = _a[_i].name;
61655                         if (ts.isBindingPattern(name) &&
61656                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61657                             hasReportedError = true;
61658                             break;
61659                         }
61660                     }
61661                     if (!hasReportedError) {
61662                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61663                     }
61664                 }
61665             }
61666         }
61667         function getTypePredicateParent(node) {
61668             switch (node.parent.kind) {
61669                 case 202 /* ArrowFunction */:
61670                 case 165 /* CallSignature */:
61671                 case 244 /* FunctionDeclaration */:
61672                 case 201 /* FunctionExpression */:
61673                 case 170 /* FunctionType */:
61674                 case 161 /* MethodDeclaration */:
61675                 case 160 /* MethodSignature */:
61676                     var parent = node.parent;
61677                     if (node === parent.type) {
61678                         return parent;
61679                     }
61680             }
61681         }
61682         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61683             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61684                 var element = _a[_i];
61685                 if (ts.isOmittedExpression(element)) {
61686                     continue;
61687                 }
61688                 var name = element.name;
61689                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61690                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61691                     return true;
61692                 }
61693                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61694                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61695                         return true;
61696                     }
61697                 }
61698             }
61699         }
61700         function checkSignatureDeclaration(node) {
61701             // Grammar checking
61702             if (node.kind === 167 /* IndexSignature */) {
61703                 checkGrammarIndexSignature(node);
61704             }
61705             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61706             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61707                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61708                 node.kind === 166 /* ConstructSignature */) {
61709                 checkGrammarFunctionLikeDeclaration(node);
61710             }
61711             var functionFlags = ts.getFunctionFlags(node);
61712             if (!(functionFlags & 4 /* Invalid */)) {
61713                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61714                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61715                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61716                 }
61717                 // Async functions prior to ES2017 require the __awaiter helper
61718                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61719                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61720                 }
61721                 // Generator functions, Async functions, and Async Generator functions prior to
61722                 // ES2015 require the __generator helper
61723                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61724                     checkExternalEmitHelpers(node, 128 /* Generator */);
61725                 }
61726             }
61727             checkTypeParameters(node.typeParameters);
61728             ts.forEach(node.parameters, checkParameter);
61729             // TODO(rbuckton): Should we start checking JSDoc types?
61730             if (node.type) {
61731                 checkSourceElement(node.type);
61732             }
61733             if (produceDiagnostics) {
61734                 checkCollisionWithArgumentsInGeneratedCode(node);
61735                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61736                 if (noImplicitAny && !returnTypeNode) {
61737                     switch (node.kind) {
61738                         case 166 /* ConstructSignature */:
61739                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61740                             break;
61741                         case 165 /* CallSignature */:
61742                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61743                             break;
61744                     }
61745                 }
61746                 if (returnTypeNode) {
61747                     var functionFlags_1 = ts.getFunctionFlags(node);
61748                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61749                         var returnType = getTypeFromTypeNode(returnTypeNode);
61750                         if (returnType === voidType) {
61751                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61752                         }
61753                         else {
61754                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61755                             // However, that would not catch the error in the following case.
61756                             //
61757                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61758                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61759                             //
61760                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61761                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61762                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61763                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61764                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61765                         }
61766                     }
61767                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61768                         checkAsyncFunctionReturnType(node, returnTypeNode);
61769                     }
61770                 }
61771                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61772                     registerForUnusedIdentifiersCheck(node);
61773                 }
61774             }
61775         }
61776         function checkClassForDuplicateDeclarations(node) {
61777             var instanceNames = ts.createUnderscoreEscapedMap();
61778             var staticNames = ts.createUnderscoreEscapedMap();
61779             // instance and static private identifiers share the same scope
61780             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61781             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61782                 var member = _a[_i];
61783                 if (member.kind === 162 /* Constructor */) {
61784                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61785                         var param = _c[_b];
61786                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61787                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61788                         }
61789                     }
61790                 }
61791                 else {
61792                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61793                     var name = member.name;
61794                     if (!name) {
61795                         return;
61796                     }
61797                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61798                         isStatic ? staticNames :
61799                             instanceNames;
61800                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61801                     if (memberName) {
61802                         switch (member.kind) {
61803                             case 163 /* GetAccessor */:
61804                                 addName(names, name, memberName, 1 /* GetAccessor */);
61805                                 break;
61806                             case 164 /* SetAccessor */:
61807                                 addName(names, name, memberName, 2 /* SetAccessor */);
61808                                 break;
61809                             case 159 /* PropertyDeclaration */:
61810                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61811                                 break;
61812                             case 161 /* MethodDeclaration */:
61813                                 addName(names, name, memberName, 8 /* Method */);
61814                                 break;
61815                         }
61816                     }
61817                 }
61818             }
61819             function addName(names, location, name, meaning) {
61820                 var prev = names.get(name);
61821                 if (prev) {
61822                     if (prev & 8 /* Method */) {
61823                         if (meaning !== 8 /* Method */) {
61824                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61825                         }
61826                     }
61827                     else if (prev & meaning) {
61828                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61829                     }
61830                     else {
61831                         names.set(name, prev | meaning);
61832                     }
61833                 }
61834                 else {
61835                     names.set(name, meaning);
61836                 }
61837             }
61838         }
61839         /**
61840          * Static members being set on a constructor function may conflict with built-in properties
61841          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
61842          * built-in properties. This check issues a transpile error when a class has a static
61843          * member with the same name as a non-writable built-in property.
61844          *
61845          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
61846          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
61847          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
61848          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
61849          */
61850         function checkClassForStaticPropertyNameConflicts(node) {
61851             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61852                 var member = _a[_i];
61853                 var memberNameNode = member.name;
61854                 var isStatic = ts.hasModifier(member, 32 /* Static */);
61855                 if (isStatic && memberNameNode) {
61856                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
61857                     switch (memberName) {
61858                         case "name":
61859                         case "length":
61860                         case "caller":
61861                         case "arguments":
61862                         case "prototype":
61863                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
61864                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
61865                             error(memberNameNode, message, memberName, className);
61866                             break;
61867                     }
61868                 }
61869             }
61870         }
61871         function checkObjectTypeForDuplicateDeclarations(node) {
61872             var names = ts.createMap();
61873             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61874                 var member = _a[_i];
61875                 if (member.kind === 158 /* PropertySignature */) {
61876                     var memberName = void 0;
61877                     var name = member.name;
61878                     switch (name.kind) {
61879                         case 10 /* StringLiteral */:
61880                         case 8 /* NumericLiteral */:
61881                             memberName = name.text;
61882                             break;
61883                         case 75 /* Identifier */:
61884                             memberName = ts.idText(name);
61885                             break;
61886                         default:
61887                             continue;
61888                     }
61889                     if (names.get(memberName)) {
61890                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
61891                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
61892                     }
61893                     else {
61894                         names.set(memberName, true);
61895                     }
61896                 }
61897             }
61898         }
61899         function checkTypeForDuplicateIndexSignatures(node) {
61900             if (node.kind === 246 /* InterfaceDeclaration */) {
61901                 var nodeSymbol = getSymbolOfNode(node);
61902                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
61903                 // to prevent this run check only for the first declaration of a given kind
61904                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
61905                     return;
61906                 }
61907             }
61908             // TypeScript 1.0 spec (April 2014)
61909             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
61910             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
61911             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
61912             if (indexSymbol) {
61913                 var seenNumericIndexer = false;
61914                 var seenStringIndexer = false;
61915                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
61916                     var decl = _a[_i];
61917                     var declaration = decl;
61918                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
61919                         switch (declaration.parameters[0].type.kind) {
61920                             case 143 /* StringKeyword */:
61921                                 if (!seenStringIndexer) {
61922                                     seenStringIndexer = true;
61923                                 }
61924                                 else {
61925                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
61926                                 }
61927                                 break;
61928                             case 140 /* NumberKeyword */:
61929                                 if (!seenNumericIndexer) {
61930                                     seenNumericIndexer = true;
61931                                 }
61932                                 else {
61933                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
61934                                 }
61935                                 break;
61936                         }
61937                     }
61938                 }
61939             }
61940         }
61941         function checkPropertyDeclaration(node) {
61942             // Grammar checking
61943             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
61944                 checkGrammarComputedPropertyName(node.name);
61945             checkVariableLikeDeclaration(node);
61946             // Private class fields transformation relies on WeakMaps.
61947             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
61948                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
61949                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
61950                 }
61951             }
61952         }
61953         function checkPropertySignature(node) {
61954             if (ts.isPrivateIdentifier(node.name)) {
61955                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
61956             }
61957             return checkPropertyDeclaration(node);
61958         }
61959         function checkMethodDeclaration(node) {
61960             // Grammar checking
61961             if (!checkGrammarMethod(node))
61962                 checkGrammarComputedPropertyName(node.name);
61963             if (ts.isPrivateIdentifier(node.name)) {
61964                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
61965             }
61966             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
61967             checkFunctionOrMethodDeclaration(node);
61968             // Abstract methods cannot have an implementation.
61969             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
61970             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
61971                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
61972             }
61973         }
61974         function checkConstructorDeclaration(node) {
61975             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
61976             checkSignatureDeclaration(node);
61977             // Grammar check for checking only related to constructorDeclaration
61978             if (!checkGrammarConstructorTypeParameters(node))
61979                 checkGrammarConstructorTypeAnnotation(node);
61980             checkSourceElement(node.body);
61981             var symbol = getSymbolOfNode(node);
61982             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
61983             // Only type check the symbol once
61984             if (node === firstDeclaration) {
61985                 checkFunctionOrConstructorSymbol(symbol);
61986             }
61987             // exit early in the case of signature - super checks are not relevant to them
61988             if (ts.nodeIsMissing(node.body)) {
61989                 return;
61990             }
61991             if (!produceDiagnostics) {
61992                 return;
61993             }
61994             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
61995                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
61996                     return true;
61997                 }
61998                 return n.kind === 159 /* PropertyDeclaration */ &&
61999                     !ts.hasModifier(n, 32 /* Static */) &&
62000                     !!n.initializer;
62001             }
62002             // TS 1.0 spec (April 2014): 8.3.2
62003             // Constructors of classes with no extends clause may not contain super calls, whereas
62004             // constructors of derived classes must contain at least one super call somewhere in their function body.
62005             var containingClassDecl = node.parent;
62006             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62007                 captureLexicalThis(node.parent, containingClassDecl);
62008                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62009                 var superCall = getSuperCallInConstructor(node);
62010                 if (superCall) {
62011                     if (classExtendsNull) {
62012                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62013                     }
62014                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62015                     // if both of the following are true:
62016                     // - The containing class is a derived class.
62017                     // - The constructor declares parameter properties
62018                     //   or the containing class declares instance member variables with initializers.
62019                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62020                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62021                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62022                     // Skip past any prologue directives to find the first statement
62023                     // to ensure that it was a super call.
62024                     if (superCallShouldBeFirst) {
62025                         var statements = node.body.statements;
62026                         var superCallStatement = void 0;
62027                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62028                             var statement = statements_3[_i];
62029                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62030                                 superCallStatement = statement;
62031                                 break;
62032                             }
62033                             if (!ts.isPrologueDirective(statement)) {
62034                                 break;
62035                             }
62036                         }
62037                         if (!superCallStatement) {
62038                             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);
62039                         }
62040                     }
62041                 }
62042                 else if (!classExtendsNull) {
62043                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62044                 }
62045             }
62046         }
62047         function checkAccessorDeclaration(node) {
62048             if (produceDiagnostics) {
62049                 // Grammar checking accessors
62050                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62051                     checkGrammarComputedPropertyName(node.name);
62052                 checkDecorators(node);
62053                 checkSignatureDeclaration(node);
62054                 if (node.kind === 163 /* GetAccessor */) {
62055                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62056                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62057                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62058                         }
62059                     }
62060                 }
62061                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62062                 // We want to perform checkComputedPropertyName for all computed properties, including
62063                 // well known symbols.
62064                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62065                     checkComputedPropertyName(node.name);
62066                 }
62067                 if (ts.isPrivateIdentifier(node.name)) {
62068                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62069                 }
62070                 if (!hasNonBindableDynamicName(node)) {
62071                     // TypeScript 1.0 spec (April 2014): 8.4.3
62072                     // Accessors for the same member name must specify the same accessibility.
62073                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62074                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62075                     if (otherAccessor) {
62076                         var nodeFlags = ts.getModifierFlags(node);
62077                         var otherFlags = ts.getModifierFlags(otherAccessor);
62078                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62079                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62080                         }
62081                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62082                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62083                         }
62084                         // TypeScript 1.0 spec (April 2014): 4.5
62085                         // If both accessors include type annotations, the specified types must be identical.
62086                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62087                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62088                     }
62089                 }
62090                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62091                 if (node.kind === 163 /* GetAccessor */) {
62092                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62093                 }
62094             }
62095             checkSourceElement(node.body);
62096         }
62097         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62098             var firstType = getAnnotatedType(first);
62099             var secondType = getAnnotatedType(second);
62100             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62101                 error(first, message);
62102             }
62103         }
62104         function checkMissingDeclaration(node) {
62105             checkDecorators(node);
62106         }
62107         function getEffectiveTypeArguments(node, typeParameters) {
62108             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62109         }
62110         function checkTypeArgumentConstraints(node, typeParameters) {
62111             var typeArguments;
62112             var mapper;
62113             var result = true;
62114             for (var i = 0; i < typeParameters.length; i++) {
62115                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62116                 if (constraint) {
62117                     if (!typeArguments) {
62118                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62119                         mapper = createTypeMapper(typeParameters, typeArguments);
62120                     }
62121                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62122                 }
62123             }
62124             return result;
62125         }
62126         function getTypeParametersForTypeReference(node) {
62127             var type = getTypeFromTypeReference(node);
62128             if (type !== errorType) {
62129                 var symbol = getNodeLinks(node).resolvedSymbol;
62130                 if (symbol) {
62131                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62132                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62133                 }
62134             }
62135             return undefined;
62136         }
62137         function checkTypeReferenceNode(node) {
62138             checkGrammarTypeArguments(node, node.typeArguments);
62139             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62140                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62141             }
62142             ts.forEach(node.typeArguments, checkSourceElement);
62143             var type = getTypeFromTypeReference(node);
62144             if (type !== errorType) {
62145                 if (node.typeArguments && produceDiagnostics) {
62146                     var typeParameters = getTypeParametersForTypeReference(node);
62147                     if (typeParameters) {
62148                         checkTypeArgumentConstraints(node, typeParameters);
62149                     }
62150                 }
62151                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62152                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62153                 }
62154             }
62155         }
62156         function getTypeArgumentConstraint(node) {
62157             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62158             if (!typeReferenceNode)
62159                 return undefined;
62160             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62161             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62162             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62163         }
62164         function checkTypeQuery(node) {
62165             getTypeFromTypeQueryNode(node);
62166         }
62167         function checkTypeLiteral(node) {
62168             ts.forEach(node.members, checkSourceElement);
62169             if (produceDiagnostics) {
62170                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62171                 checkIndexConstraints(type);
62172                 checkTypeForDuplicateIndexSignatures(node);
62173                 checkObjectTypeForDuplicateDeclarations(node);
62174             }
62175         }
62176         function checkArrayType(node) {
62177             checkSourceElement(node.elementType);
62178         }
62179         function checkTupleType(node) {
62180             var elementTypes = node.elementTypes;
62181             var seenOptionalElement = false;
62182             for (var i = 0; i < elementTypes.length; i++) {
62183                 var e = elementTypes[i];
62184                 if (e.kind === 177 /* RestType */) {
62185                     if (i !== elementTypes.length - 1) {
62186                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62187                         break;
62188                     }
62189                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62190                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62191                     }
62192                 }
62193                 else if (e.kind === 176 /* OptionalType */) {
62194                     seenOptionalElement = true;
62195                 }
62196                 else if (seenOptionalElement) {
62197                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62198                     break;
62199                 }
62200             }
62201             ts.forEach(node.elementTypes, checkSourceElement);
62202         }
62203         function checkUnionOrIntersectionType(node) {
62204             ts.forEach(node.types, checkSourceElement);
62205         }
62206         function checkIndexedAccessIndexType(type, accessNode) {
62207             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62208                 return type;
62209             }
62210             // Check if the index type is assignable to 'keyof T' for the object type.
62211             var objectType = type.objectType;
62212             var indexType = type.indexType;
62213             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62214                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62215                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62216                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62217                 }
62218                 return type;
62219             }
62220             // Check if we're indexing with a numeric type and if either object or index types
62221             // is a generic type with a constraint that has a numeric index signature.
62222             var apparentObjectType = getApparentType(objectType);
62223             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62224                 return type;
62225             }
62226             if (isGenericObjectType(objectType)) {
62227                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62228                 if (propertyName_1) {
62229                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62230                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62231                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62232                         return errorType;
62233                     }
62234                 }
62235             }
62236             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62237             return errorType;
62238         }
62239         function checkIndexedAccessType(node) {
62240             checkSourceElement(node.objectType);
62241             checkSourceElement(node.indexType);
62242             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62243         }
62244         function checkMappedType(node) {
62245             checkSourceElement(node.typeParameter);
62246             checkSourceElement(node.type);
62247             if (!node.type) {
62248                 reportImplicitAny(node, anyType);
62249             }
62250             var type = getTypeFromMappedTypeNode(node);
62251             var constraintType = getConstraintTypeFromMappedType(type);
62252             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62253         }
62254         function checkThisType(node) {
62255             getTypeFromThisTypeNode(node);
62256         }
62257         function checkTypeOperator(node) {
62258             checkGrammarTypeOperatorNode(node);
62259             checkSourceElement(node.type);
62260         }
62261         function checkConditionalType(node) {
62262             ts.forEachChild(node, checkSourceElement);
62263         }
62264         function checkInferType(node) {
62265             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62266                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62267             }
62268             checkSourceElement(node.typeParameter);
62269             registerForUnusedIdentifiersCheck(node);
62270         }
62271         function checkImportType(node) {
62272             checkSourceElement(node.argument);
62273             getTypeFromTypeNode(node);
62274         }
62275         function isPrivateWithinAmbient(node) {
62276             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62277         }
62278         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62279             var flags = ts.getCombinedModifierFlags(n);
62280             // children of classes (even ambient classes) should not be marked as ambient or export
62281             // because those flags have no useful semantics there.
62282             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62283                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62284                 n.parent.kind !== 214 /* ClassExpression */ &&
62285                 n.flags & 8388608 /* Ambient */) {
62286                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62287                     // It is nested in an ambient context, which means it is automatically exported
62288                     flags |= 1 /* Export */;
62289                 }
62290                 flags |= 2 /* Ambient */;
62291             }
62292             return flags & flagsToCheck;
62293         }
62294         function checkFunctionOrConstructorSymbol(symbol) {
62295             if (!produceDiagnostics) {
62296                 return;
62297             }
62298             function getCanonicalOverload(overloads, implementation) {
62299                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62300                 // Error on all deviations from this canonical set of flags
62301                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62302                 // report the errors on those. To achieve this, we will say that the implementation is
62303                 // the canonical signature only if it is in the same container as the first overload
62304                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62305                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62306             }
62307             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62308                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62309                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62310                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62311                 if (someButNotAllOverloadFlags !== 0) {
62312                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62313                     ts.forEach(overloads, function (o) {
62314                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62315                         if (deviation & 1 /* Export */) {
62316                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62317                         }
62318                         else if (deviation & 2 /* Ambient */) {
62319                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62320                         }
62321                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62322                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62323                         }
62324                         else if (deviation & 128 /* Abstract */) {
62325                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62326                         }
62327                     });
62328                 }
62329             }
62330             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62331                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62332                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62333                     ts.forEach(overloads, function (o) {
62334                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62335                         if (deviation) {
62336                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62337                         }
62338                     });
62339                 }
62340             }
62341             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62342             var someNodeFlags = 0 /* None */;
62343             var allNodeFlags = flagsToCheck;
62344             var someHaveQuestionToken = false;
62345             var allHaveQuestionToken = true;
62346             var hasOverloads = false;
62347             var bodyDeclaration;
62348             var lastSeenNonAmbientDeclaration;
62349             var previousDeclaration;
62350             var declarations = symbol.declarations;
62351             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62352             function reportImplementationExpectedError(node) {
62353                 if (node.name && ts.nodeIsMissing(node.name)) {
62354                     return;
62355                 }
62356                 var seen = false;
62357                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62358                     if (seen) {
62359                         return c;
62360                     }
62361                     else {
62362                         seen = c === node;
62363                     }
62364                 });
62365                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62366                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62367                 if (subsequentNode && subsequentNode.pos === node.end) {
62368                     if (subsequentNode.kind === node.kind) {
62369                         var errorNode_1 = subsequentNode.name || subsequentNode;
62370                         var subsequentName = subsequentNode.name;
62371                         if (node.name && subsequentName && (
62372                         // both are private identifiers
62373                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62374                             // Both are computed property names
62375                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62376                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62377                             // Both are literal property names that are the same.
62378                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62379                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62380                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62381                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62382                             // we can get here in two cases
62383                             // 1. mixed static and instance class members
62384                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62385                             // here we'll report error only for the first case since for second we should already report error in binder
62386                             if (reportError) {
62387                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62388                                 error(errorNode_1, diagnostic);
62389                             }
62390                             return;
62391                         }
62392                         if (ts.nodeIsPresent(subsequentNode.body)) {
62393                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62394                             return;
62395                         }
62396                     }
62397                 }
62398                 var errorNode = node.name || node;
62399                 if (isConstructor) {
62400                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62401                 }
62402                 else {
62403                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62404                     // the node in question is abstract.
62405                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62406                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62407                     }
62408                     else {
62409                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62410                     }
62411                 }
62412             }
62413             var duplicateFunctionDeclaration = false;
62414             var multipleConstructorImplementation = false;
62415             var hasNonAmbientClass = false;
62416             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62417                 var current = declarations_4[_i];
62418                 var node = current;
62419                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62420                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62421                 if (inAmbientContextOrInterface) {
62422                     // check if declarations are consecutive only if they are non-ambient
62423                     // 1. ambient declarations can be interleaved
62424                     // i.e. this is legal
62425                     //     declare function foo();
62426                     //     declare function bar();
62427                     //     declare function foo();
62428                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62429                     previousDeclaration = undefined;
62430                 }
62431                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62432                     hasNonAmbientClass = true;
62433                 }
62434                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62435                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62436                     someNodeFlags |= currentNodeFlags;
62437                     allNodeFlags &= currentNodeFlags;
62438                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62439                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62440                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62441                         if (isConstructor) {
62442                             multipleConstructorImplementation = true;
62443                         }
62444                         else {
62445                             duplicateFunctionDeclaration = true;
62446                         }
62447                     }
62448                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62449                         reportImplementationExpectedError(previousDeclaration);
62450                     }
62451                     if (ts.nodeIsPresent(node.body)) {
62452                         if (!bodyDeclaration) {
62453                             bodyDeclaration = node;
62454                         }
62455                     }
62456                     else {
62457                         hasOverloads = true;
62458                     }
62459                     previousDeclaration = node;
62460                     if (!inAmbientContextOrInterface) {
62461                         lastSeenNonAmbientDeclaration = node;
62462                     }
62463                 }
62464             }
62465             if (multipleConstructorImplementation) {
62466                 ts.forEach(declarations, function (declaration) {
62467                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62468                 });
62469             }
62470             if (duplicateFunctionDeclaration) {
62471                 ts.forEach(declarations, function (declaration) {
62472                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62473                 });
62474             }
62475             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62476                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62477                 // TODO: The below just replicates our older error from when classes and functions were
62478                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62479                 // might be warranted. :shrug:
62480                 ts.forEach(declarations, function (declaration) {
62481                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62482                 });
62483             }
62484             // Abstract methods can't have an implementation -- in particular, they don't need one.
62485             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62486                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62487                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62488             }
62489             if (hasOverloads) {
62490                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62491                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62492                 if (bodyDeclaration) {
62493                     var signatures = getSignaturesOfSymbol(symbol);
62494                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62495                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62496                         var signature = signatures_10[_a];
62497                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62498                             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));
62499                             break;
62500                         }
62501                     }
62502                 }
62503             }
62504         }
62505         function checkExportsOnMergedDeclarations(node) {
62506             if (!produceDiagnostics) {
62507                 return;
62508             }
62509             // if localSymbol is defined on node then node itself is exported - check is required
62510             var symbol = node.localSymbol;
62511             if (!symbol) {
62512                 // local symbol is undefined => this declaration is non-exported.
62513                 // however symbol might contain other declarations that are exported
62514                 symbol = getSymbolOfNode(node);
62515                 if (!symbol.exportSymbol) {
62516                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62517                     return;
62518                 }
62519             }
62520             // run the check only for the first declaration in the list
62521             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62522                 return;
62523             }
62524             var exportedDeclarationSpaces = 0 /* None */;
62525             var nonExportedDeclarationSpaces = 0 /* None */;
62526             var defaultExportedDeclarationSpaces = 0 /* None */;
62527             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62528                 var d = _a[_i];
62529                 var declarationSpaces = getDeclarationSpaces(d);
62530                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62531                 if (effectiveDeclarationFlags & 1 /* Export */) {
62532                     if (effectiveDeclarationFlags & 512 /* Default */) {
62533                         defaultExportedDeclarationSpaces |= declarationSpaces;
62534                     }
62535                     else {
62536                         exportedDeclarationSpaces |= declarationSpaces;
62537                     }
62538                 }
62539                 else {
62540                     nonExportedDeclarationSpaces |= declarationSpaces;
62541                 }
62542             }
62543             // Spaces for anything not declared a 'default export'.
62544             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62545             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62546             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62547             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62548                 // declaration spaces for exported and non-exported declarations intersect
62549                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62550                     var d = _c[_b];
62551                     var declarationSpaces = getDeclarationSpaces(d);
62552                     var name = ts.getNameOfDeclaration(d);
62553                     // Only error on the declarations that contributed to the intersecting spaces.
62554                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62555                         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));
62556                     }
62557                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62558                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62559                     }
62560                 }
62561             }
62562             function getDeclarationSpaces(decl) {
62563                 var d = decl;
62564                 switch (d.kind) {
62565                     case 246 /* InterfaceDeclaration */:
62566                     case 247 /* TypeAliasDeclaration */:
62567                     // A jsdoc typedef and callback are, by definition, type aliases.
62568                     // falls through
62569                     case 322 /* JSDocTypedefTag */:
62570                     case 315 /* JSDocCallbackTag */:
62571                     case 316 /* JSDocEnumTag */:
62572                         return 2 /* ExportType */;
62573                     case 249 /* ModuleDeclaration */:
62574                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62575                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62576                             : 4 /* ExportNamespace */;
62577                     case 245 /* ClassDeclaration */:
62578                     case 248 /* EnumDeclaration */:
62579                     case 284 /* EnumMember */:
62580                         return 2 /* ExportType */ | 1 /* ExportValue */;
62581                     case 290 /* SourceFile */:
62582                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62583                     case 259 /* ExportAssignment */:
62584                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62585                         if (!ts.isEntityNameExpression(d.expression)) {
62586                             return 1 /* ExportValue */;
62587                         }
62588                         d = d.expression;
62589                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62590                     // falls through
62591                     case 253 /* ImportEqualsDeclaration */:
62592                     case 256 /* NamespaceImport */:
62593                     case 255 /* ImportClause */:
62594                         var result_10 = 0 /* None */;
62595                         var target = resolveAlias(getSymbolOfNode(d));
62596                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62597                         return result_10;
62598                     case 242 /* VariableDeclaration */:
62599                     case 191 /* BindingElement */:
62600                     case 244 /* FunctionDeclaration */:
62601                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62602                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62603                         // Identifiers are used as declarations of assignment declarations whose parents may be
62604                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62605                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62606                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62607                         // all of which are pretty much always values, or at least imply a value meaning.
62608                         // It may be apprpriate to treat these as aliases in the future.
62609                         return 1 /* ExportValue */;
62610                     default:
62611                         return ts.Debug.failBadSyntaxKind(d);
62612                 }
62613             }
62614         }
62615         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62616             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62617             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62618         }
62619         /**
62620          * Gets the "promised type" of a promise.
62621          * @param type The type of the promise.
62622          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62623          */
62624         function getPromisedTypeOfPromise(type, errorNode) {
62625             //
62626             //  { // type
62627             //      then( // thenFunction
62628             //          onfulfilled: ( // onfulfilledParameterType
62629             //              value: T // valueParameterType
62630             //          ) => any
62631             //      ): any;
62632             //  }
62633             //
62634             if (isTypeAny(type)) {
62635                 return undefined;
62636             }
62637             var typeAsPromise = type;
62638             if (typeAsPromise.promisedTypeOfPromise) {
62639                 return typeAsPromise.promisedTypeOfPromise;
62640             }
62641             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62642                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62643             }
62644             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62645             if (isTypeAny(thenFunction)) {
62646                 return undefined;
62647             }
62648             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62649             if (thenSignatures.length === 0) {
62650                 if (errorNode) {
62651                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62652                 }
62653                 return undefined;
62654             }
62655             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62656             if (isTypeAny(onfulfilledParameterType)) {
62657                 return undefined;
62658             }
62659             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62660             if (onfulfilledParameterSignatures.length === 0) {
62661                 if (errorNode) {
62662                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62663                 }
62664                 return undefined;
62665             }
62666             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62667         }
62668         /**
62669          * Gets the "awaited type" of a type.
62670          * @param type The type to await.
62671          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62672          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62673          * The runtime behavior of the `await` keyword.
62674          */
62675         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62676             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62677             return awaitedType || errorType;
62678         }
62679         /**
62680          * Determines whether a type has a callable `then` member.
62681          */
62682         function isThenableType(type) {
62683             var thenFunction = getTypeOfPropertyOfType(type, "then");
62684             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62685         }
62686         /**
62687          * Gets the "awaited type" of a type.
62688          *
62689          * The "awaited type" of an expression is its "promised type" if the expression is a
62690          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62691          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62692          * non-promise type is found.
62693          *
62694          * This is used to reflect the runtime behavior of the `await` keyword.
62695          */
62696         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62697             if (isTypeAny(type)) {
62698                 return type;
62699             }
62700             var typeAsAwaitable = type;
62701             if (typeAsAwaitable.awaitedTypeOfType) {
62702                 return typeAsAwaitable.awaitedTypeOfType;
62703             }
62704             // For a union, get a union of the awaited types of each constituent.
62705             //
62706             return typeAsAwaitable.awaitedTypeOfType =
62707                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62708         }
62709         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62710             var typeAsAwaitable = type;
62711             if (typeAsAwaitable.awaitedTypeOfType) {
62712                 return typeAsAwaitable.awaitedTypeOfType;
62713             }
62714             var promisedType = getPromisedTypeOfPromise(type);
62715             if (promisedType) {
62716                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62717                     // Verify that we don't have a bad actor in the form of a promise whose
62718                     // promised type is the same as the promise type, or a mutually recursive
62719                     // promise. If so, we return undefined as we cannot guess the shape. If this
62720                     // were the actual case in the JavaScript, this Promise would never resolve.
62721                     //
62722                     // An example of a bad actor with a singly-recursive promise type might
62723                     // be:
62724                     //
62725                     //  interface BadPromise {
62726                     //      then(
62727                     //          onfulfilled: (value: BadPromise) => any,
62728                     //          onrejected: (error: any) => any): BadPromise;
62729                     //  }
62730                     //
62731                     // The above interface will pass the PromiseLike check, and return a
62732                     // promised type of `BadPromise`. Since this is a self reference, we
62733                     // don't want to keep recursing ad infinitum.
62734                     //
62735                     // An example of a bad actor in the form of a mutually-recursive
62736                     // promise type might be:
62737                     //
62738                     //  interface BadPromiseA {
62739                     //      then(
62740                     //          onfulfilled: (value: BadPromiseB) => any,
62741                     //          onrejected: (error: any) => any): BadPromiseB;
62742                     //  }
62743                     //
62744                     //  interface BadPromiseB {
62745                     //      then(
62746                     //          onfulfilled: (value: BadPromiseA) => any,
62747                     //          onrejected: (error: any) => any): BadPromiseA;
62748                     //  }
62749                     //
62750                     if (errorNode) {
62751                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62752                     }
62753                     return undefined;
62754                 }
62755                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62756                 // See the comments above for more information.
62757                 awaitedTypeStack.push(type.id);
62758                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62759                 awaitedTypeStack.pop();
62760                 if (!awaitedType) {
62761                     return undefined;
62762                 }
62763                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62764             }
62765             // The type was not a promise, so it could not be unwrapped any further.
62766             // As long as the type does not have a callable "then" property, it is
62767             // safe to return the type; otherwise, an error is reported and we return
62768             // undefined.
62769             //
62770             // An example of a non-promise "thenable" might be:
62771             //
62772             //  await { then(): void {} }
62773             //
62774             // The "thenable" does not match the minimal definition for a promise. When
62775             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62776             // will never settle. We treat this as an error to help flag an early indicator
62777             // of a runtime problem. If the user wants to return this value from an async
62778             // function, they would need to wrap it in some other value. If they want it to
62779             // be treated as a promise, they can cast to <any>.
62780             if (isThenableType(type)) {
62781                 if (errorNode) {
62782                     if (!diagnosticMessage)
62783                         return ts.Debug.fail();
62784                     error(errorNode, diagnosticMessage, arg0);
62785                 }
62786                 return undefined;
62787             }
62788             return typeAsAwaitable.awaitedTypeOfType = type;
62789         }
62790         /**
62791          * Checks the return type of an async function to ensure it is a compatible
62792          * Promise implementation.
62793          *
62794          * This checks that an async function has a valid Promise-compatible return type.
62795          * An async function has a valid Promise-compatible return type if the resolved value
62796          * of the return type has a construct signature that takes in an `initializer` function
62797          * that in turn supplies a `resolve` function as one of its arguments and results in an
62798          * object with a callable `then` signature.
62799          *
62800          * @param node The signature to check
62801          */
62802         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62803             // As part of our emit for an async function, we will need to emit the entity name of
62804             // the return type annotation as an expression. To meet the necessary runtime semantics
62805             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62806             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62807             //
62808             // An example might be (from lib.es6.d.ts):
62809             //
62810             //  interface Promise<T> { ... }
62811             //  interface PromiseConstructor {
62812             //      new <T>(...): Promise<T>;
62813             //  }
62814             //  declare var Promise: PromiseConstructor;
62815             //
62816             // When an async function declares a return type annotation of `Promise<T>`, we
62817             // need to get the type of the `Promise` variable declaration above, which would
62818             // be `PromiseConstructor`.
62819             //
62820             // The same case applies to a class:
62821             //
62822             //  declare class Promise<T> {
62823             //      constructor(...);
62824             //      then<U>(...): Promise<U>;
62825             //  }
62826             //
62827             var returnType = getTypeFromTypeNode(returnTypeNode);
62828             if (languageVersion >= 2 /* ES2015 */) {
62829                 if (returnType === errorType) {
62830                     return;
62831                 }
62832                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
62833                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
62834                     // The promise type was not a valid type reference to the global promise type, so we
62835                     // report an error and return the unknown type.
62836                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
62837                     return;
62838                 }
62839             }
62840             else {
62841                 // Always mark the type node as referenced if it points to a value
62842                 markTypeNodeAsReferenced(returnTypeNode);
62843                 if (returnType === errorType) {
62844                     return;
62845                 }
62846                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
62847                 if (promiseConstructorName === undefined) {
62848                     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));
62849                     return;
62850                 }
62851                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
62852                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
62853                 if (promiseConstructorType === errorType) {
62854                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
62855                         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);
62856                     }
62857                     else {
62858                         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));
62859                     }
62860                     return;
62861                 }
62862                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
62863                 if (globalPromiseConstructorLikeType === emptyObjectType) {
62864                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
62865                     // compatibility with __awaiter.
62866                     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));
62867                     return;
62868                 }
62869                 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)) {
62870                     return;
62871                 }
62872                 // Verify there is no local declaration that could collide with the promise constructor.
62873                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
62874                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
62875                 if (collidingSymbol) {
62876                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
62877                     return;
62878                 }
62879             }
62880             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);
62881         }
62882         /** Check a decorator */
62883         function checkDecorator(node) {
62884             var signature = getResolvedSignature(node);
62885             var returnType = getReturnTypeOfSignature(signature);
62886             if (returnType.flags & 1 /* Any */) {
62887                 return;
62888             }
62889             var expectedReturnType;
62890             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
62891             var errorInfo;
62892             switch (node.parent.kind) {
62893                 case 245 /* ClassDeclaration */:
62894                     var classSymbol = getSymbolOfNode(node.parent);
62895                     var classConstructorType = getTypeOfSymbol(classSymbol);
62896                     expectedReturnType = getUnionType([classConstructorType, voidType]);
62897                     break;
62898                 case 156 /* Parameter */:
62899                     expectedReturnType = voidType;
62900                     errorInfo = ts.chainDiagnosticMessages(
62901                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
62902                     break;
62903                 case 159 /* PropertyDeclaration */:
62904                     expectedReturnType = voidType;
62905                     errorInfo = ts.chainDiagnosticMessages(
62906                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
62907                     break;
62908                 case 161 /* MethodDeclaration */:
62909                 case 163 /* GetAccessor */:
62910                 case 164 /* SetAccessor */:
62911                     var methodType = getTypeOfNode(node.parent);
62912                     var descriptorType = createTypedPropertyDescriptorType(methodType);
62913                     expectedReturnType = getUnionType([descriptorType, voidType]);
62914                     break;
62915                 default:
62916                     return ts.Debug.fail();
62917             }
62918             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
62919         }
62920         /**
62921          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
62922          * marked as referenced to prevent import elision.
62923          */
62924         function markTypeNodeAsReferenced(node) {
62925             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
62926         }
62927         function markEntityNameOrEntityExpressionAsReference(typeName) {
62928             if (!typeName)
62929                 return;
62930             var rootName = ts.getFirstIdentifier(typeName);
62931             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
62932             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
62933             if (rootSymbol
62934                 && rootSymbol.flags & 2097152 /* Alias */
62935                 && symbolIsValue(rootSymbol)
62936                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
62937                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
62938                 markAliasSymbolAsReferenced(rootSymbol);
62939             }
62940         }
62941         /**
62942          * This function marks the type used for metadata decorator as referenced if it is import
62943          * from external module.
62944          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
62945          * union and intersection type
62946          * @param node
62947          */
62948         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
62949             var entityName = getEntityNameForDecoratorMetadata(node);
62950             if (entityName && ts.isEntityName(entityName)) {
62951                 markEntityNameOrEntityExpressionAsReference(entityName);
62952             }
62953         }
62954         function getEntityNameForDecoratorMetadata(node) {
62955             if (node) {
62956                 switch (node.kind) {
62957                     case 179 /* IntersectionType */:
62958                     case 178 /* UnionType */:
62959                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
62960                     case 180 /* ConditionalType */:
62961                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
62962                     case 182 /* ParenthesizedType */:
62963                         return getEntityNameForDecoratorMetadata(node.type);
62964                     case 169 /* TypeReference */:
62965                         return node.typeName;
62966                 }
62967             }
62968         }
62969         function getEntityNameForDecoratorMetadataFromTypeList(types) {
62970             var commonEntityName;
62971             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
62972                 var typeNode = types_20[_i];
62973                 while (typeNode.kind === 182 /* ParenthesizedType */) {
62974                     typeNode = typeNode.type; // Skip parens if need be
62975                 }
62976                 if (typeNode.kind === 137 /* NeverKeyword */) {
62977                     continue; // Always elide `never` from the union/intersection if possible
62978                 }
62979                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
62980                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
62981                 }
62982                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
62983                 if (!individualEntityName) {
62984                     // Individual is something like string number
62985                     // So it would be serialized to either that type or object
62986                     // Safe to return here
62987                     return undefined;
62988                 }
62989                 if (commonEntityName) {
62990                     // Note this is in sync with the transformation that happens for type node.
62991                     // Keep this in sync with serializeUnionOrIntersectionType
62992                     // Verify if they refer to same entity and is identifier
62993                     // return undefined if they dont match because we would emit object
62994                     if (!ts.isIdentifier(commonEntityName) ||
62995                         !ts.isIdentifier(individualEntityName) ||
62996                         commonEntityName.escapedText !== individualEntityName.escapedText) {
62997                         return undefined;
62998                     }
62999                 }
63000                 else {
63001                     commonEntityName = individualEntityName;
63002                 }
63003             }
63004             return commonEntityName;
63005         }
63006         function getParameterTypeNodeForDecoratorCheck(node) {
63007             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63008             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63009         }
63010         /** Check the decorators of a node */
63011         function checkDecorators(node) {
63012             if (!node.decorators) {
63013                 return;
63014             }
63015             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63016             // checkGrammarDecorators.
63017             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63018                 return;
63019             }
63020             if (!compilerOptions.experimentalDecorators) {
63021                 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);
63022             }
63023             var firstDecorator = node.decorators[0];
63024             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63025             if (node.kind === 156 /* Parameter */) {
63026                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63027             }
63028             if (compilerOptions.emitDecoratorMetadata) {
63029                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63030                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63031                 switch (node.kind) {
63032                     case 245 /* ClassDeclaration */:
63033                         var constructor = ts.getFirstConstructorWithBody(node);
63034                         if (constructor) {
63035                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63036                                 var parameter = _a[_i];
63037                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63038                             }
63039                         }
63040                         break;
63041                     case 163 /* GetAccessor */:
63042                     case 164 /* SetAccessor */:
63043                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63044                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63045                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63046                         break;
63047                     case 161 /* MethodDeclaration */:
63048                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63049                             var parameter = _c[_b];
63050                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63051                         }
63052                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63053                         break;
63054                     case 159 /* PropertyDeclaration */:
63055                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63056                         break;
63057                     case 156 /* Parameter */:
63058                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63059                         var containingSignature = node.parent;
63060                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63061                             var parameter = _e[_d];
63062                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63063                         }
63064                         break;
63065                 }
63066             }
63067             ts.forEach(node.decorators, checkDecorator);
63068         }
63069         function checkFunctionDeclaration(node) {
63070             if (produceDiagnostics) {
63071                 checkFunctionOrMethodDeclaration(node);
63072                 checkGrammarForGenerator(node);
63073                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63074                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63075             }
63076         }
63077         function checkJSDocTypeAliasTag(node) {
63078             if (!node.typeExpression) {
63079                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63080                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63081             }
63082             if (node.name) {
63083                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63084             }
63085             checkSourceElement(node.typeExpression);
63086         }
63087         function checkJSDocTemplateTag(node) {
63088             checkSourceElement(node.constraint);
63089             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63090                 var tp = _a[_i];
63091                 checkSourceElement(tp);
63092             }
63093         }
63094         function checkJSDocTypeTag(node) {
63095             checkSourceElement(node.typeExpression);
63096         }
63097         function checkJSDocParameterTag(node) {
63098             checkSourceElement(node.typeExpression);
63099             if (!ts.getParameterSymbolFromJSDoc(node)) {
63100                 var decl = ts.getHostSignatureFromJSDoc(node);
63101                 // don't issue an error for invalid hosts -- just functions --
63102                 // and give a better error message when the host function mentions `arguments`
63103                 // but the tag doesn't have an array type
63104                 if (decl) {
63105                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63106                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63107                         return;
63108                     }
63109                     if (!containsArgumentsReference(decl)) {
63110                         if (ts.isQualifiedName(node.name)) {
63111                             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));
63112                         }
63113                         else {
63114                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63115                         }
63116                     }
63117                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63118                         node.typeExpression && node.typeExpression.type &&
63119                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63120                         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));
63121                     }
63122                 }
63123             }
63124         }
63125         function checkJSDocPropertyTag(node) {
63126             checkSourceElement(node.typeExpression);
63127         }
63128         function checkJSDocFunctionType(node) {
63129             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63130                 reportImplicitAny(node, anyType);
63131             }
63132             checkSignatureDeclaration(node);
63133         }
63134         function checkJSDocImplementsTag(node) {
63135             var classLike = ts.getEffectiveJSDocHost(node);
63136             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63137                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63138             }
63139         }
63140         function checkJSDocAugmentsTag(node) {
63141             var classLike = ts.getEffectiveJSDocHost(node);
63142             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63143                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63144                 return;
63145             }
63146             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63147             ts.Debug.assert(augmentsTags.length > 0);
63148             if (augmentsTags.length > 1) {
63149                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63150             }
63151             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63152             var extend = ts.getClassExtendsHeritageElement(classLike);
63153             if (extend) {
63154                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63155                 if (className && name.escapedText !== className.escapedText) {
63156                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63157                 }
63158             }
63159         }
63160         function getIdentifierFromEntityNameExpression(node) {
63161             switch (node.kind) {
63162                 case 75 /* Identifier */:
63163                     return node;
63164                 case 194 /* PropertyAccessExpression */:
63165                     return node.name;
63166                 default:
63167                     return undefined;
63168             }
63169         }
63170         function checkFunctionOrMethodDeclaration(node) {
63171             checkDecorators(node);
63172             checkSignatureDeclaration(node);
63173             var functionFlags = ts.getFunctionFlags(node);
63174             // Do not use hasDynamicName here, because that returns false for well known symbols.
63175             // We want to perform checkComputedPropertyName for all computed properties, including
63176             // well known symbols.
63177             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63178                 // This check will account for methods in class/interface declarations,
63179                 // as well as accessors in classes/object literals
63180                 checkComputedPropertyName(node.name);
63181             }
63182             if (!hasNonBindableDynamicName(node)) {
63183                 // first we want to check the local symbol that contain this declaration
63184                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63185                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63186                 var symbol = getSymbolOfNode(node);
63187                 var localSymbol = node.localSymbol || symbol;
63188                 // Since the javascript won't do semantic analysis like typescript,
63189                 // if the javascript file comes before the typescript file and both contain same name functions,
63190                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63191                 var firstDeclaration = ts.find(localSymbol.declarations, 
63192                 // Get first non javascript function declaration
63193                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63194                 // Only type check the symbol once
63195                 if (node === firstDeclaration) {
63196                     checkFunctionOrConstructorSymbol(localSymbol);
63197                 }
63198                 if (symbol.parent) {
63199                     // run check once for the first declaration
63200                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63201                         // run check on export symbol to check that modifiers agree across all exported declarations
63202                         checkFunctionOrConstructorSymbol(symbol);
63203                     }
63204                 }
63205             }
63206             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63207             checkSourceElement(body);
63208             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63209             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63210                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63211                 // in an ambient context
63212                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63213                     reportImplicitAny(node, anyType);
63214                 }
63215                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63216                     // A generator with a body and no type annotation can still cause errors. It can error if the
63217                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63218                     // yielded values. The only way to trigger these errors is to try checking its return type.
63219                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63220                 }
63221             }
63222             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63223             if (ts.isInJSFile(node)) {
63224                 var typeTag = ts.getJSDocTypeTag(node);
63225                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63226                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63227                 }
63228             }
63229         }
63230         function registerForUnusedIdentifiersCheck(node) {
63231             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63232             if (produceDiagnostics) {
63233                 var sourceFile = ts.getSourceFileOfNode(node);
63234                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63235                 if (!potentiallyUnusedIdentifiers) {
63236                     potentiallyUnusedIdentifiers = [];
63237                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63238                 }
63239                 // TODO: GH#22580
63240                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63241                 potentiallyUnusedIdentifiers.push(node);
63242             }
63243         }
63244         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63245             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63246                 var node = potentiallyUnusedIdentifiers_1[_i];
63247                 switch (node.kind) {
63248                     case 245 /* ClassDeclaration */:
63249                     case 214 /* ClassExpression */:
63250                         checkUnusedClassMembers(node, addDiagnostic);
63251                         checkUnusedTypeParameters(node, addDiagnostic);
63252                         break;
63253                     case 290 /* SourceFile */:
63254                     case 249 /* ModuleDeclaration */:
63255                     case 223 /* Block */:
63256                     case 251 /* CaseBlock */:
63257                     case 230 /* ForStatement */:
63258                     case 231 /* ForInStatement */:
63259                     case 232 /* ForOfStatement */:
63260                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63261                         break;
63262                     case 162 /* Constructor */:
63263                     case 201 /* FunctionExpression */:
63264                     case 244 /* FunctionDeclaration */:
63265                     case 202 /* ArrowFunction */:
63266                     case 161 /* MethodDeclaration */:
63267                     case 163 /* GetAccessor */:
63268                     case 164 /* SetAccessor */:
63269                         if (node.body) { // Don't report unused parameters in overloads
63270                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63271                         }
63272                         checkUnusedTypeParameters(node, addDiagnostic);
63273                         break;
63274                     case 160 /* MethodSignature */:
63275                     case 165 /* CallSignature */:
63276                     case 166 /* ConstructSignature */:
63277                     case 170 /* FunctionType */:
63278                     case 171 /* ConstructorType */:
63279                     case 247 /* TypeAliasDeclaration */:
63280                     case 246 /* InterfaceDeclaration */:
63281                         checkUnusedTypeParameters(node, addDiagnostic);
63282                         break;
63283                     case 181 /* InferType */:
63284                         checkUnusedInferTypeParameter(node, addDiagnostic);
63285                         break;
63286                     default:
63287                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63288                 }
63289             }
63290         }
63291         function errorUnusedLocal(declaration, name, addDiagnostic) {
63292             var node = ts.getNameOfDeclaration(declaration) || declaration;
63293             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63294             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63295         }
63296         function isIdentifierThatStartsWithUnderscore(node) {
63297             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63298         }
63299         function checkUnusedClassMembers(node, addDiagnostic) {
63300             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63301                 var member = _a[_i];
63302                 switch (member.kind) {
63303                     case 161 /* MethodDeclaration */:
63304                     case 159 /* PropertyDeclaration */:
63305                     case 163 /* GetAccessor */:
63306                     case 164 /* SetAccessor */:
63307                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63308                             // Already would have reported an error on the getter.
63309                             break;
63310                         }
63311                         var symbol = getSymbolOfNode(member);
63312                         if (!symbol.isReferenced
63313                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63314                             && !(member.flags & 8388608 /* Ambient */)) {
63315                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63316                         }
63317                         break;
63318                     case 162 /* Constructor */:
63319                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63320                             var parameter = _c[_b];
63321                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63322                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63323                             }
63324                         }
63325                         break;
63326                     case 167 /* IndexSignature */:
63327                     case 222 /* SemicolonClassElement */:
63328                         // Can't be private
63329                         break;
63330                     default:
63331                         ts.Debug.fail();
63332                 }
63333             }
63334         }
63335         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63336             var typeParameter = node.typeParameter;
63337             if (isTypeParameterUnused(typeParameter)) {
63338                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63339             }
63340         }
63341         function checkUnusedTypeParameters(node, addDiagnostic) {
63342             // Only report errors on the last declaration for the type parameter container;
63343             // this ensures that all uses have been accounted for.
63344             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63345                 return;
63346             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63347             var seenParentsWithEveryUnused = new ts.NodeSet();
63348             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63349                 var typeParameter = typeParameters_3[_i];
63350                 if (!isTypeParameterUnused(typeParameter))
63351                     continue;
63352                 var name = ts.idText(typeParameter.name);
63353                 var parent = typeParameter.parent;
63354                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63355                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63356                         var range = ts.isJSDocTemplateTag(parent)
63357                             // Whole @template tag
63358                             ? ts.rangeOfNode(parent)
63359                             // Include the `<>` in the error message
63360                             : ts.rangeOfTypeParameters(parent.typeParameters);
63361                         var only = parent.typeParameters.length === 1;
63362                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63363                         var arg0 = only ? name : undefined;
63364                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63365                     }
63366                 }
63367                 else {
63368                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63369                 }
63370             }
63371         }
63372         function isTypeParameterUnused(typeParameter) {
63373             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63374         }
63375         function addToGroup(map, key, value, getKey) {
63376             var keyString = String(getKey(key));
63377             var group = map.get(keyString);
63378             if (group) {
63379                 group[1].push(value);
63380             }
63381             else {
63382                 map.set(keyString, [key, [value]]);
63383             }
63384         }
63385         function tryGetRootParameterDeclaration(node) {
63386             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63387         }
63388         function isValidUnusedLocalDeclaration(declaration) {
63389             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63390                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63391                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63392                         ts.isForOfStatement(ancestor) ? true : "quit";
63393                 });
63394             }
63395             return ts.isAmbientModule(declaration) ||
63396                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63397         }
63398         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63399             // 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.
63400             var unusedImports = ts.createMap();
63401             var unusedDestructures = ts.createMap();
63402             var unusedVariables = ts.createMap();
63403             nodeWithLocals.locals.forEach(function (local) {
63404                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63405                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63406                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63407                     return;
63408                 }
63409                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63410                     var declaration = _a[_i];
63411                     if (isValidUnusedLocalDeclaration(declaration)) {
63412                         continue;
63413                     }
63414                     if (isImportedDeclaration(declaration)) {
63415                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63416                     }
63417                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63418                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63419                         var lastElement = ts.last(declaration.parent.elements);
63420                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63421                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63422                         }
63423                     }
63424                     else if (ts.isVariableDeclaration(declaration)) {
63425                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63426                     }
63427                     else {
63428                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63429                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63430                         if (parameter && name) {
63431                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63432                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63433                             }
63434                         }
63435                         else {
63436                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63437                         }
63438                     }
63439                 }
63440             });
63441             unusedImports.forEach(function (_a) {
63442                 var importClause = _a[0], unuseds = _a[1];
63443                 var importDecl = importClause.parent;
63444                 var nDeclarations = (importClause.name ? 1 : 0) +
63445                     (importClause.namedBindings ?
63446                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63447                         : 0);
63448                 if (nDeclarations === unuseds.length) {
63449                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63450                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63451                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63452                 }
63453                 else {
63454                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63455                         var unused = unuseds_1[_i];
63456                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63457                     }
63458                 }
63459             });
63460             unusedDestructures.forEach(function (_a) {
63461                 var bindingPattern = _a[0], bindingElements = _a[1];
63462                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63463                 if (bindingPattern.elements.length === bindingElements.length) {
63464                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63465                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63466                     }
63467                     else {
63468                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63469                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63470                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63471                     }
63472                 }
63473                 else {
63474                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63475                         var e = bindingElements_1[_i];
63476                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63477                     }
63478                 }
63479             });
63480             unusedVariables.forEach(function (_a) {
63481                 var declarationList = _a[0], declarations = _a[1];
63482                 if (declarationList.declarations.length === declarations.length) {
63483                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63484                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63485                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63486                 }
63487                 else {
63488                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63489                         var decl = declarations_5[_i];
63490                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63491                     }
63492                 }
63493             });
63494         }
63495         function bindingNameText(name) {
63496             switch (name.kind) {
63497                 case 75 /* Identifier */:
63498                     return ts.idText(name);
63499                 case 190 /* ArrayBindingPattern */:
63500                 case 189 /* ObjectBindingPattern */:
63501                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63502                 default:
63503                     return ts.Debug.assertNever(name);
63504             }
63505         }
63506         function isImportedDeclaration(node) {
63507             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63508         }
63509         function importClauseFromImported(decl) {
63510             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63511         }
63512         function checkBlock(node) {
63513             // Grammar checking for SyntaxKind.Block
63514             if (node.kind === 223 /* Block */) {
63515                 checkGrammarStatementInAmbientContext(node);
63516             }
63517             if (ts.isFunctionOrModuleBlock(node)) {
63518                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63519                 ts.forEach(node.statements, checkSourceElement);
63520                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63521             }
63522             else {
63523                 ts.forEach(node.statements, checkSourceElement);
63524             }
63525             if (node.locals) {
63526                 registerForUnusedIdentifiersCheck(node);
63527             }
63528         }
63529         function checkCollisionWithArgumentsInGeneratedCode(node) {
63530             // no rest parameters \ declaration context \ overload - no codegen impact
63531             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63532                 return;
63533             }
63534             ts.forEach(node.parameters, function (p) {
63535                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63536                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63537                 }
63538             });
63539         }
63540         function needCollisionCheckForIdentifier(node, identifier, name) {
63541             if (!(identifier && identifier.escapedText === name)) {
63542                 return false;
63543             }
63544             if (node.kind === 159 /* PropertyDeclaration */ ||
63545                 node.kind === 158 /* PropertySignature */ ||
63546                 node.kind === 161 /* MethodDeclaration */ ||
63547                 node.kind === 160 /* MethodSignature */ ||
63548                 node.kind === 163 /* GetAccessor */ ||
63549                 node.kind === 164 /* SetAccessor */) {
63550                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63551                 return false;
63552             }
63553             if (node.flags & 8388608 /* Ambient */) {
63554                 // ambient context - no codegen impact
63555                 return false;
63556             }
63557             var root = ts.getRootDeclaration(node);
63558             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63559                 // just an overload - no codegen impact
63560                 return false;
63561             }
63562             return true;
63563         }
63564         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63565         function checkIfThisIsCapturedInEnclosingScope(node) {
63566             ts.findAncestor(node, function (current) {
63567                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63568                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63569                     if (isDeclaration_1) {
63570                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63571                     }
63572                     else {
63573                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63574                     }
63575                     return true;
63576                 }
63577                 return false;
63578             });
63579         }
63580         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63581             ts.findAncestor(node, function (current) {
63582                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63583                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63584                     if (isDeclaration_2) {
63585                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63586                     }
63587                     else {
63588                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63589                     }
63590                     return true;
63591                 }
63592                 return false;
63593             });
63594         }
63595         function checkWeakMapCollision(node) {
63596             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63597             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63598                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63599             }
63600         }
63601         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63602             // No need to check for require or exports for ES6 modules and later
63603             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63604                 return;
63605             }
63606             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63607                 return;
63608             }
63609             // Uninstantiated modules shouldnt do this check
63610             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63611                 return;
63612             }
63613             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63614             var parent = getDeclarationContainer(node);
63615             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63616                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63617                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63618             }
63619         }
63620         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63621             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63622                 return;
63623             }
63624             // Uninstantiated modules shouldnt do this check
63625             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63626                 return;
63627             }
63628             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63629             var parent = getDeclarationContainer(node);
63630             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63631                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63632                 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));
63633             }
63634         }
63635         function checkVarDeclaredNamesNotShadowed(node) {
63636             // - ScriptBody : StatementList
63637             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63638             // also occurs in the VarDeclaredNames of StatementList.
63639             // - Block : { StatementList }
63640             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63641             // also occurs in the VarDeclaredNames of StatementList.
63642             // Variable declarations are hoisted to the top of their function scope. They can shadow
63643             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63644             // by the binder as the declaration scope is different.
63645             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63646             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63647             // block declared value. this is fine for let, but not const.
63648             // Only consider declarations with initializers, uninitialized const declarations will not
63649             // step on a let/const variable.
63650             // Do not consider const and const declarations, as duplicate block-scoped declarations
63651             // are handled by the binder.
63652             // We are only looking for const declarations that step on let\const declarations from a
63653             // different scope. e.g.:
63654             //      {
63655             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63656             //          const x = 0; // symbol for this declaration will be 'symbol'
63657             //      }
63658             // skip block-scoped variables and parameters
63659             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63660                 return;
63661             }
63662             // skip variable declarations that don't have initializers
63663             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63664             // so we'll always treat binding elements as initialized
63665             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63666                 return;
63667             }
63668             var symbol = getSymbolOfNode(node);
63669             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63670                 if (!ts.isIdentifier(node.name))
63671                     return ts.Debug.fail();
63672                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63673                 if (localDeclarationSymbol &&
63674                     localDeclarationSymbol !== symbol &&
63675                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63676                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63677                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63678                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63679                             ? varDeclList.parent.parent
63680                             : undefined;
63681                         // names of block-scoped and function scoped variables can collide only
63682                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63683                         var namesShareScope = container &&
63684                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63685                                 container.kind === 250 /* ModuleBlock */ ||
63686                                 container.kind === 249 /* ModuleDeclaration */ ||
63687                                 container.kind === 290 /* SourceFile */);
63688                         // here we know that function scoped variable is shadowed by block scoped one
63689                         // if they are defined in the same scope - binder has already reported redeclaration error
63690                         // otherwise if variable has an initializer - show error that initialization will fail
63691                         // since LHS will be block scoped name instead of function scoped
63692                         if (!namesShareScope) {
63693                             var name = symbolToString(localDeclarationSymbol);
63694                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63695                         }
63696                     }
63697                 }
63698             }
63699         }
63700         function convertAutoToAny(type) {
63701             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63702         }
63703         // Check variable, parameter, or property declaration
63704         function checkVariableLikeDeclaration(node) {
63705             checkDecorators(node);
63706             if (!ts.isBindingElement(node)) {
63707                 checkSourceElement(node.type);
63708             }
63709             // JSDoc `function(string, string): string` syntax results in parameters with no name
63710             if (!node.name) {
63711                 return;
63712             }
63713             // For a computed property, just check the initializer and exit
63714             // Do not use hasDynamicName here, because that returns false for well known symbols.
63715             // We want to perform checkComputedPropertyName for all computed properties, including
63716             // well known symbols.
63717             if (node.name.kind === 154 /* ComputedPropertyName */) {
63718                 checkComputedPropertyName(node.name);
63719                 if (node.initializer) {
63720                     checkExpressionCached(node.initializer);
63721                 }
63722             }
63723             if (node.kind === 191 /* BindingElement */) {
63724                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63725                     checkExternalEmitHelpers(node, 4 /* Rest */);
63726                 }
63727                 // check computed properties inside property names of binding elements
63728                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63729                     checkComputedPropertyName(node.propertyName);
63730                 }
63731                 // check private/protected variable access
63732                 var parent = node.parent.parent;
63733                 var parentType = getTypeForBindingElementParent(parent);
63734                 var name = node.propertyName || node.name;
63735                 if (parentType && !ts.isBindingPattern(name)) {
63736                     var exprType = getLiteralTypeFromPropertyName(name);
63737                     if (isTypeUsableAsPropertyName(exprType)) {
63738                         var nameText = getPropertyNameFromType(exprType);
63739                         var property = getPropertyOfType(parentType, nameText);
63740                         if (property) {
63741                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63742                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63743                         }
63744                     }
63745                 }
63746             }
63747             // For a binding pattern, check contained binding elements
63748             if (ts.isBindingPattern(node.name)) {
63749                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63750                     checkExternalEmitHelpers(node, 512 /* Read */);
63751                 }
63752                 ts.forEach(node.name.elements, checkSourceElement);
63753             }
63754             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63755             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63756                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63757                 return;
63758             }
63759             // For a binding pattern, validate the initializer and exit
63760             if (ts.isBindingPattern(node.name)) {
63761                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63762                 var needCheckWidenedType = node.name.elements.length === 0;
63763                 if (needCheckInitializer || needCheckWidenedType) {
63764                     // Don't validate for-in initializer as it is already an error
63765                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63766                     if (needCheckInitializer) {
63767                         var initializerType = checkExpressionCached(node.initializer);
63768                         if (strictNullChecks && needCheckWidenedType) {
63769                             checkNonNullNonVoidType(initializerType, node);
63770                         }
63771                         else {
63772                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63773                         }
63774                     }
63775                     // check the binding pattern with empty elements
63776                     if (needCheckWidenedType) {
63777                         if (ts.isArrayBindingPattern(node.name)) {
63778                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63779                         }
63780                         else if (strictNullChecks) {
63781                             checkNonNullNonVoidType(widenedType, node);
63782                         }
63783                     }
63784                 }
63785                 return;
63786             }
63787             var symbol = getSymbolOfNode(node);
63788             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63789             if (node === symbol.valueDeclaration) {
63790                 // Node is the primary declaration of the symbol, just validate the initializer
63791                 // Don't validate for-in initializer as it is already an error
63792                 var initializer = ts.getEffectiveInitializer(node);
63793                 if (initializer) {
63794                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63795                         ts.isObjectLiteralExpression(initializer) &&
63796                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63797                         ts.hasEntries(symbol.exports);
63798                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63799                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63800                     }
63801                 }
63802                 if (symbol.declarations.length > 1) {
63803                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63804                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63805                     }
63806                 }
63807             }
63808             else {
63809                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63810                 // initializer is consistent with type associated with the node
63811                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63812                 if (type !== errorType && declarationType !== errorType &&
63813                     !isTypeIdenticalTo(type, declarationType) &&
63814                     !(symbol.flags & 67108864 /* Assignment */)) {
63815                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63816                 }
63817                 if (node.initializer) {
63818                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
63819                 }
63820                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
63821                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63822                 }
63823             }
63824             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
63825                 // We know we don't have a binding pattern or computed name here
63826                 checkExportsOnMergedDeclarations(node);
63827                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
63828                     checkVarDeclaredNamesNotShadowed(node);
63829                 }
63830                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63831                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63832                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
63833                     potentialWeakMapCollisions.push(node);
63834                 }
63835             }
63836         }
63837         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
63838             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
63839             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
63840                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
63841                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
63842             var declName = ts.declarationNameToString(nextDeclarationName);
63843             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
63844             if (firstDeclaration) {
63845                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
63846             }
63847         }
63848         function areDeclarationFlagsIdentical(left, right) {
63849             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
63850                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
63851                 // Differences in optionality between parameters and variables are allowed.
63852                 return true;
63853             }
63854             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
63855                 return false;
63856             }
63857             var interestingFlags = 8 /* Private */ |
63858                 16 /* Protected */ |
63859                 256 /* Async */ |
63860                 128 /* Abstract */ |
63861                 64 /* Readonly */ |
63862                 32 /* Static */;
63863             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
63864         }
63865         function checkVariableDeclaration(node) {
63866             checkGrammarVariableDeclaration(node);
63867             return checkVariableLikeDeclaration(node);
63868         }
63869         function checkBindingElement(node) {
63870             checkGrammarBindingElement(node);
63871             return checkVariableLikeDeclaration(node);
63872         }
63873         function checkVariableStatement(node) {
63874             // Grammar checking
63875             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
63876                 checkGrammarForDisallowedLetOrConstStatement(node);
63877             ts.forEach(node.declarationList.declarations, checkSourceElement);
63878         }
63879         function checkExpressionStatement(node) {
63880             // Grammar checking
63881             checkGrammarStatementInAmbientContext(node);
63882             checkExpression(node.expression);
63883         }
63884         function checkIfStatement(node) {
63885             // Grammar checking
63886             checkGrammarStatementInAmbientContext(node);
63887             var type = checkTruthinessExpression(node.expression);
63888             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
63889             checkSourceElement(node.thenStatement);
63890             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
63891                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
63892             }
63893             checkSourceElement(node.elseStatement);
63894         }
63895         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
63896             if (!strictNullChecks) {
63897                 return;
63898             }
63899             var testedNode = ts.isIdentifier(condExpr)
63900                 ? condExpr
63901                 : ts.isPropertyAccessExpression(condExpr)
63902                     ? condExpr.name
63903                     : undefined;
63904             if (!testedNode) {
63905                 return;
63906             }
63907             var possiblyFalsy = getFalsyFlags(type);
63908             if (possiblyFalsy) {
63909                 return;
63910             }
63911             // While it technically should be invalid for any known-truthy value
63912             // to be tested, we de-scope to functions unrefenced in the block as a
63913             // heuristic to identify the most common bugs. There are too many
63914             // false positives for values sourced from type definitions without
63915             // strictNullChecks otherwise.
63916             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
63917             if (callSignatures.length === 0) {
63918                 return;
63919             }
63920             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
63921             if (!testedFunctionSymbol) {
63922                 return;
63923             }
63924             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
63925                 if (ts.isIdentifier(childNode)) {
63926                     var childSymbol = getSymbolAtLocation(childNode);
63927                     if (childSymbol && childSymbol === testedFunctionSymbol) {
63928                         // If the test was a simple identifier, the above check is sufficient
63929                         if (ts.isIdentifier(condExpr)) {
63930                             return true;
63931                         }
63932                         // Otherwise we need to ensure the symbol is called on the same target
63933                         var testedExpression = testedNode.parent;
63934                         var childExpression = childNode.parent;
63935                         while (testedExpression && childExpression) {
63936                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
63937                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
63938                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
63939                             }
63940                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
63941                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
63942                                     return false;
63943                                 }
63944                                 childExpression = childExpression.expression;
63945                                 testedExpression = testedExpression.expression;
63946                             }
63947                             else {
63948                                 return false;
63949                             }
63950                         }
63951                     }
63952                 }
63953                 return ts.forEachChild(childNode, check);
63954             });
63955             if (!functionIsUsedInBody) {
63956                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
63957             }
63958         }
63959         function checkDoStatement(node) {
63960             // Grammar checking
63961             checkGrammarStatementInAmbientContext(node);
63962             checkSourceElement(node.statement);
63963             checkTruthinessExpression(node.expression);
63964         }
63965         function checkWhileStatement(node) {
63966             // Grammar checking
63967             checkGrammarStatementInAmbientContext(node);
63968             checkTruthinessExpression(node.expression);
63969             checkSourceElement(node.statement);
63970         }
63971         function checkTruthinessOfType(type, node) {
63972             if (type.flags & 16384 /* Void */) {
63973                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
63974             }
63975             return type;
63976         }
63977         function checkTruthinessExpression(node, checkMode) {
63978             return checkTruthinessOfType(checkExpression(node, checkMode), node);
63979         }
63980         function checkForStatement(node) {
63981             // Grammar checking
63982             if (!checkGrammarStatementInAmbientContext(node)) {
63983                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
63984                     checkGrammarVariableDeclarationList(node.initializer);
63985                 }
63986             }
63987             if (node.initializer) {
63988                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
63989                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
63990                 }
63991                 else {
63992                     checkExpression(node.initializer);
63993                 }
63994             }
63995             if (node.condition)
63996                 checkTruthinessExpression(node.condition);
63997             if (node.incrementor)
63998                 checkExpression(node.incrementor);
63999             checkSourceElement(node.statement);
64000             if (node.locals) {
64001                 registerForUnusedIdentifiersCheck(node);
64002             }
64003         }
64004         function checkForOfStatement(node) {
64005             checkGrammarForInOrForOfStatement(node);
64006             if (node.awaitModifier) {
64007                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64008                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64009                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64010                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64011                 }
64012             }
64013             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64014                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64015                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64016             }
64017             // Check the LHS and RHS
64018             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64019             // via checkRightHandSideOfForOf.
64020             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64021             // Then check that the RHS is assignable to it.
64022             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64023                 checkForInOrForOfVariableDeclaration(node);
64024             }
64025             else {
64026                 var varExpr = node.initializer;
64027                 var iteratedType = checkRightHandSideOfForOf(node);
64028                 // There may be a destructuring assignment on the left side
64029                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64030                     // iteratedType may be undefined. In this case, we still want to check the structure of
64031                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64032                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64033                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64034                 }
64035                 else {
64036                     var leftType = checkExpression(varExpr);
64037                     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);
64038                     // iteratedType will be undefined if the rightType was missing properties/signatures
64039                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64040                     // because we accessed properties from anyType, or it may have led to an error inside
64041                     // getElementTypeOfIterable.
64042                     if (iteratedType) {
64043                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64044                     }
64045                 }
64046             }
64047             checkSourceElement(node.statement);
64048             if (node.locals) {
64049                 registerForUnusedIdentifiersCheck(node);
64050             }
64051         }
64052         function checkForInStatement(node) {
64053             // Grammar checking
64054             checkGrammarForInOrForOfStatement(node);
64055             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64056             // TypeScript 1.0 spec (April 2014): 5.4
64057             // In a 'for-in' statement of the form
64058             // for (let VarDecl in Expr) Statement
64059             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64060             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64061             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64062                 var variable = node.initializer.declarations[0];
64063                 if (variable && ts.isBindingPattern(variable.name)) {
64064                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64065                 }
64066                 checkForInOrForOfVariableDeclaration(node);
64067             }
64068             else {
64069                 // In a 'for-in' statement of the form
64070                 // for (Var in Expr) Statement
64071                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64072                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64073                 var varExpr = node.initializer;
64074                 var leftType = checkExpression(varExpr);
64075                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64076                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64077                 }
64078                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64079                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64080                 }
64081                 else {
64082                     // run check only former check succeeded to avoid cascading errors
64083                     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);
64084                 }
64085             }
64086             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64087             // in this case error about missing name is already reported - do not report extra one
64088             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64089                 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));
64090             }
64091             checkSourceElement(node.statement);
64092             if (node.locals) {
64093                 registerForUnusedIdentifiersCheck(node);
64094             }
64095         }
64096         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64097             var variableDeclarationList = iterationStatement.initializer;
64098             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64099             if (variableDeclarationList.declarations.length >= 1) {
64100                 var decl = variableDeclarationList.declarations[0];
64101                 checkVariableDeclaration(decl);
64102             }
64103         }
64104         function checkRightHandSideOfForOf(statement) {
64105             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64106             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64107         }
64108         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64109             if (isTypeAny(inputType)) {
64110                 return inputType;
64111             }
64112             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64113         }
64114         /**
64115          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64116          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64117          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64118          */
64119         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64120             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64121             if (inputType === neverType) {
64122                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64123                 return undefined;
64124             }
64125             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64126             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64127             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64128             // or higher, when inside of an async generator or for-await-if, or when
64129             // downlevelIteration is requested.
64130             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64131                 // We only report errors for an invalid iterable type in ES2015 or higher.
64132                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64133                 if (checkAssignability) {
64134                     if (iterationTypes) {
64135                         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 :
64136                             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 :
64137                                 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 :
64138                                     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 :
64139                                         undefined;
64140                         if (diagnostic) {
64141                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64142                         }
64143                     }
64144                 }
64145                 if (iterationTypes || uplevelIteration) {
64146                     return iterationTypes && iterationTypes.yieldType;
64147                 }
64148             }
64149             var arrayType = inputType;
64150             var reportedError = false;
64151             var hasStringConstituent = false;
64152             // If strings are permitted, remove any string-like constituents from the array type.
64153             // This allows us to find other non-string element types from an array unioned with
64154             // a string.
64155             if (use & 4 /* AllowsStringInputFlag */) {
64156                 if (arrayType.flags & 1048576 /* Union */) {
64157                     // After we remove all types that are StringLike, we will know if there was a string constituent
64158                     // based on whether the result of filter is a new array.
64159                     var arrayTypes = inputType.types;
64160                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64161                     if (filteredTypes !== arrayTypes) {
64162                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64163                     }
64164                 }
64165                 else if (arrayType.flags & 132 /* StringLike */) {
64166                     arrayType = neverType;
64167                 }
64168                 hasStringConstituent = arrayType !== inputType;
64169                 if (hasStringConstituent) {
64170                     if (languageVersion < 1 /* ES5 */) {
64171                         if (errorNode) {
64172                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64173                             reportedError = true;
64174                         }
64175                     }
64176                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64177                     // arrayOrStringType was a string.
64178                     if (arrayType.flags & 131072 /* Never */) {
64179                         return stringType;
64180                     }
64181                 }
64182             }
64183             if (!isArrayLikeType(arrayType)) {
64184                 if (errorNode && !reportedError) {
64185                     // Which error we report depends on whether we allow strings or if there was a
64186                     // string constituent. For example, if the input type is number | string, we
64187                     // want to say that number is not an array type. But if the input was just
64188                     // number and string input is allowed, we want to say that number is not an
64189                     // array type or a string type.
64190                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64191                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64192                         ? downlevelIteration
64193                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64194                             : yieldType
64195                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64196                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64197                         : downlevelIteration
64198                             ? [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]
64199                             : yieldType
64200                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64201                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64202                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64203                 }
64204                 return hasStringConstituent ? stringType : undefined;
64205             }
64206             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64207             if (hasStringConstituent && arrayElementType) {
64208                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64209                 if (arrayElementType.flags & 132 /* StringLike */) {
64210                     return stringType;
64211                 }
64212                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64213             }
64214             return arrayElementType;
64215         }
64216         /**
64217          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64218          */
64219         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64220             if (isTypeAny(inputType)) {
64221                 return undefined;
64222             }
64223             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64224             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64225         }
64226         function createIterationTypes(yieldType, returnType, nextType) {
64227             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64228             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64229             // as it is combined via `getIntersectionType` when merging iteration types.
64230             if (yieldType === void 0) { yieldType = neverType; }
64231             if (returnType === void 0) { returnType = neverType; }
64232             if (nextType === void 0) { nextType = unknownType; }
64233             // Use the cache only for intrinsic types to keep it small as they are likely to be
64234             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64235             // are also cached on the type they are requested for, so we shouldn't need to maintain
64236             // the cache for less-frequently used types.
64237             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64238                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64239                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64240                 var id = getTypeListId([yieldType, returnType, nextType]);
64241                 var iterationTypes = iterationTypesCache.get(id);
64242                 if (!iterationTypes) {
64243                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64244                     iterationTypesCache.set(id, iterationTypes);
64245                 }
64246                 return iterationTypes;
64247             }
64248             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64249         }
64250         /**
64251          * Combines multiple `IterationTypes` records.
64252          *
64253          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64254          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64255          * for the combined iteration types.
64256          */
64257         function combineIterationTypes(array) {
64258             var yieldTypes;
64259             var returnTypes;
64260             var nextTypes;
64261             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64262                 var iterationTypes = array_10[_i];
64263                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64264                     continue;
64265                 }
64266                 if (iterationTypes === anyIterationTypes) {
64267                     return anyIterationTypes;
64268                 }
64269                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64270                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64271                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64272             }
64273             if (yieldTypes || returnTypes || nextTypes) {
64274                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64275             }
64276             return noIterationTypes;
64277         }
64278         function getCachedIterationTypes(type, cacheKey) {
64279             return type[cacheKey];
64280         }
64281         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64282             return type[cacheKey] = cachedTypes;
64283         }
64284         /**
64285          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64286          *
64287          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64288          *
64289          * Another thing to note is that at any step of this process, we could run into a dead end,
64290          * meaning either the property is missing, or we run into the anyType. If either of these things
64291          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64292          * is missing, and the previous step did not result in `any`, then we also give an error if the
64293          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64294          * type.
64295          *
64296          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64297          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64298          * method.
64299          *
64300          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64301          *
64302          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64303          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64304          */
64305         function getIterationTypesOfIterable(type, use, errorNode) {
64306             if (isTypeAny(type)) {
64307                 return anyIterationTypes;
64308             }
64309             if (!(type.flags & 1048576 /* Union */)) {
64310                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64311                 if (iterationTypes_1 === noIterationTypes) {
64312                     if (errorNode) {
64313                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64314                     }
64315                     return undefined;
64316                 }
64317                 return iterationTypes_1;
64318             }
64319             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64320             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64321             if (cachedTypes)
64322                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64323             var allIterationTypes;
64324             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64325                 var constituent = _a[_i];
64326                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64327                 if (iterationTypes_2 === noIterationTypes) {
64328                     if (errorNode) {
64329                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64330                         errorNode = undefined;
64331                     }
64332                 }
64333                 else {
64334                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64335                 }
64336             }
64337             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64338             setCachedIterationTypes(type, cacheKey, iterationTypes);
64339             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64340         }
64341         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64342             if (iterationTypes === noIterationTypes)
64343                 return noIterationTypes;
64344             if (iterationTypes === anyIterationTypes)
64345                 return anyIterationTypes;
64346             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64347             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64348         }
64349         /**
64350          * Gets the *yield*, *return*, and *next* types from a non-union type.
64351          *
64352          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64353          * returned to indicate to the caller that it should report an error. Otherwise, an
64354          * `IterationTypes` record is returned.
64355          *
64356          * NOTE: You probably don't want to call this directly and should be calling
64357          * `getIterationTypesOfIterable` instead.
64358          */
64359         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64360             if (isTypeAny(type)) {
64361                 return anyIterationTypes;
64362             }
64363             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64364                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64365                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64366                 if (iterationTypes) {
64367                     return iterationTypes;
64368                 }
64369             }
64370             if (use & 1 /* AllowsSyncIterablesFlag */) {
64371                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64372                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64373                 if (iterationTypes) {
64374                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64375                         // for a sync iterable in an async context, only use the cached types if they are valid.
64376                         if (iterationTypes !== noIterationTypes) {
64377                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64378                         }
64379                     }
64380                     else {
64381                         return iterationTypes;
64382                     }
64383                 }
64384             }
64385             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64386                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64387                 if (iterationTypes !== noIterationTypes) {
64388                     return iterationTypes;
64389                 }
64390             }
64391             if (use & 1 /* AllowsSyncIterablesFlag */) {
64392                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64393                 if (iterationTypes !== noIterationTypes) {
64394                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64395                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64396                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64397                             : noIterationTypes);
64398                     }
64399                     else {
64400                         return iterationTypes;
64401                     }
64402                 }
64403             }
64404             return noIterationTypes;
64405         }
64406         /**
64407          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64408          * `AsyncIterable`-like type from the cache.
64409          *
64410          * NOTE: You probably don't want to call this directly and should be calling
64411          * `getIterationTypesOfIterable` instead.
64412          */
64413         function getIterationTypesOfIterableCached(type, resolver) {
64414             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64415         }
64416         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64417             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64418                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64419             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64420         }
64421         /**
64422          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64423          * type from from common heuristics.
64424          *
64425          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64426          * returned. If we found iteration types, an `IterationTypes` record is returned.
64427          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64428          * exhaustive analysis.
64429          *
64430          * NOTE: You probably don't want to call this directly and should be calling
64431          * `getIterationTypesOfIterable` instead.
64432          */
64433         function getIterationTypesOfIterableFast(type, resolver) {
64434             // As an optimization, if the type is an instantiation of one of the following global types, then
64435             // just grab its related type argument:
64436             // - `Iterable<T>` or `AsyncIterable<T>`
64437             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64438             var globalType;
64439             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64440                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64441                 var yieldType = getTypeArguments(type)[0];
64442                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64443                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64444                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64445                 // different definitions.
64446                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64447                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64448             }
64449             // As an optimization, if the type is an instantiation of the following global type, then
64450             // just grab its related type arguments:
64451             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64452             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64453                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64454                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64455             }
64456         }
64457         /**
64458          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64459          * type from its members.
64460          *
64461          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64462          * record is returned. Otherwise, `noIterationTypes` is returned.
64463          *
64464          * NOTE: You probably don't want to call this directly and should be calling
64465          * `getIterationTypesOfIterable` instead.
64466          */
64467         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64468             var _a;
64469             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64470             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64471             if (isTypeAny(methodType)) {
64472                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64473             }
64474             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64475             if (!ts.some(signatures)) {
64476                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64477             }
64478             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64479             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64480             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64481         }
64482         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64483             var message = allowAsyncIterables
64484                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64485                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64486             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64487         }
64488         /**
64489          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64490          *
64491          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64492          * record is returned. Otherwise, `undefined` is returned.
64493          */
64494         function getIterationTypesOfIterator(type, resolver, errorNode) {
64495             if (isTypeAny(type)) {
64496                 return anyIterationTypes;
64497             }
64498             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64499                 getIterationTypesOfIteratorFast(type, resolver) ||
64500                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64501             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64502         }
64503         /**
64504          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64505          * cache.
64506          *
64507          * NOTE: You probably don't want to call this directly and should be calling
64508          * `getIterationTypesOfIterator` instead.
64509          */
64510         function getIterationTypesOfIteratorCached(type, resolver) {
64511             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64512         }
64513         /**
64514          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64515          * cache or from common heuristics.
64516          *
64517          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64518          * returned. If we found iteration types, an `IterationTypes` record is returned.
64519          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64520          * exhaustive analysis.
64521          *
64522          * NOTE: You probably don't want to call this directly and should be calling
64523          * `getIterationTypesOfIterator` instead.
64524          */
64525         function getIterationTypesOfIteratorFast(type, resolver) {
64526             // As an optimization, if the type is an instantiation of one of the following global types,
64527             // then just grab its related type argument:
64528             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64529             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64530             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64531             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64532             if (isReferenceToType(type, globalType)) {
64533                 var yieldType = getTypeArguments(type)[0];
64534                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64535                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64536                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64537                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64538                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64539                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64540                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64541             }
64542             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64543                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64544                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64545                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64546             }
64547         }
64548         function isIteratorResult(type, kind) {
64549             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64550             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64551             // > If the end was not reached `done` is `false` and a value is available.
64552             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64553             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64554             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64555         }
64556         function isYieldIteratorResult(type) {
64557             return isIteratorResult(type, 0 /* Yield */);
64558         }
64559         function isReturnIteratorResult(type) {
64560             return isIteratorResult(type, 1 /* Return */);
64561         }
64562         /**
64563          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64564          *
64565          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64566          * returned to indicate to the caller that it should handle the error. Otherwise, an
64567          * `IterationTypes` record is returned.
64568          */
64569         function getIterationTypesOfIteratorResult(type) {
64570             if (isTypeAny(type)) {
64571                 return anyIterationTypes;
64572             }
64573             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64574             if (cachedTypes) {
64575                 return cachedTypes;
64576             }
64577             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64578             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64579             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64580                 var yieldType_1 = getTypeArguments(type)[0];
64581                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64582             }
64583             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64584                 var returnType_1 = getTypeArguments(type)[0];
64585                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64586             }
64587             // Choose any constituents that can produce the requested iteration type.
64588             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64589             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64590             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64591             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64592             if (!yieldType && !returnType) {
64593                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64594             }
64595             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64596             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64597             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64598             // > `value` property.
64599             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64600         }
64601         /**
64602          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64603          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64604          *
64605          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64606          * record is returned. Otherwise, we return `undefined`.
64607          */
64608         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64609             var method = getPropertyOfType(type, methodName);
64610             // Ignore 'return' or 'throw' if they are missing.
64611             if (!method && methodName !== "next") {
64612                 return undefined;
64613             }
64614             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64615                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64616                 : undefined;
64617             if (isTypeAny(methodType)) {
64618                 // `return()` and `throw()` don't provide a *next* type.
64619                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64620             }
64621             // Both async and non-async iterators *must* have a `next` method.
64622             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64623             if (methodSignatures.length === 0) {
64624                 if (errorNode) {
64625                     var diagnostic = methodName === "next"
64626                         ? resolver.mustHaveANextMethodDiagnostic
64627                         : resolver.mustBeAMethodDiagnostic;
64628                     error(errorNode, diagnostic, methodName);
64629                 }
64630                 return methodName === "next" ? anyIterationTypes : undefined;
64631             }
64632             // Extract the first parameter and return type of each signature.
64633             var methodParameterTypes;
64634             var methodReturnTypes;
64635             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64636                 var signature = methodSignatures_1[_i];
64637                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64638                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64639                 }
64640                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64641             }
64642             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64643             // `return()` method, respectively.
64644             var returnTypes;
64645             var nextType;
64646             if (methodName !== "throw") {
64647                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64648                 if (methodName === "next") {
64649                     // The value of `next(value)` is *not* awaited by async generators
64650                     nextType = methodParameterType;
64651                 }
64652                 else if (methodName === "return") {
64653                     // The value of `return(value)` *is* awaited by async generators
64654                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64655                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64656                 }
64657             }
64658             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64659             var yieldType;
64660             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64661             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64662             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64663             if (iterationTypes === noIterationTypes) {
64664                 if (errorNode) {
64665                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64666                 }
64667                 yieldType = anyType;
64668                 returnTypes = ts.append(returnTypes, anyType);
64669             }
64670             else {
64671                 yieldType = iterationTypes.yieldType;
64672                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64673             }
64674             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64675         }
64676         /**
64677          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64678          * type from its members.
64679          *
64680          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64681          * record is returned. Otherwise, `noIterationTypes` is returned.
64682          *
64683          * NOTE: You probably don't want to call this directly and should be calling
64684          * `getIterationTypesOfIterator` instead.
64685          */
64686         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64687             var iterationTypes = combineIterationTypes([
64688                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64689                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64690                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64691             ]);
64692             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64693         }
64694         /**
64695          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64696          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64697          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64698          */
64699         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64700             if (isTypeAny(returnType)) {
64701                 return undefined;
64702             }
64703             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64704             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64705         }
64706         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64707             if (isTypeAny(type)) {
64708                 return anyIterationTypes;
64709             }
64710             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64711             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64712             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64713                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64714         }
64715         function checkBreakOrContinueStatement(node) {
64716             // Grammar checking
64717             if (!checkGrammarStatementInAmbientContext(node))
64718                 checkGrammarBreakOrContinueStatement(node);
64719             // TODO: Check that target label is valid
64720         }
64721         function unwrapReturnType(returnType, functionFlags) {
64722             var _a, _b;
64723             var isGenerator = !!(functionFlags & 1 /* Generator */);
64724             var isAsync = !!(functionFlags & 2 /* Async */);
64725             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64726                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64727                     returnType;
64728         }
64729         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64730             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64731             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64732         }
64733         function checkReturnStatement(node) {
64734             var _a;
64735             // Grammar checking
64736             if (checkGrammarStatementInAmbientContext(node)) {
64737                 return;
64738             }
64739             var func = ts.getContainingFunction(node);
64740             if (!func) {
64741                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64742                 return;
64743             }
64744             var signature = getSignatureFromDeclaration(func);
64745             var returnType = getReturnTypeOfSignature(signature);
64746             var functionFlags = ts.getFunctionFlags(func);
64747             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64748                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64749                 if (func.kind === 164 /* SetAccessor */) {
64750                     if (node.expression) {
64751                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64752                     }
64753                 }
64754                 else if (func.kind === 162 /* Constructor */) {
64755                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64756                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64757                     }
64758                 }
64759                 else if (getReturnTypeFromAnnotation(func)) {
64760                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64761                     var unwrappedExprType = functionFlags & 2 /* Async */
64762                         ? 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)
64763                         : exprType;
64764                     if (unwrappedReturnType) {
64765                         // If the function has a return type, but promisedType is
64766                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64767                         // so we don't need to report one here.
64768                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64769                     }
64770                 }
64771             }
64772             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64773                 // The function has a return type, but the return statement doesn't have an expression.
64774                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64775             }
64776         }
64777         function checkWithStatement(node) {
64778             // Grammar checking for withStatement
64779             if (!checkGrammarStatementInAmbientContext(node)) {
64780                 if (node.flags & 32768 /* AwaitContext */) {
64781                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64782                 }
64783             }
64784             checkExpression(node.expression);
64785             var sourceFile = ts.getSourceFileOfNode(node);
64786             if (!hasParseDiagnostics(sourceFile)) {
64787                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64788                 var end = node.statement.pos;
64789                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64790             }
64791         }
64792         function checkSwitchStatement(node) {
64793             // Grammar checking
64794             checkGrammarStatementInAmbientContext(node);
64795             var firstDefaultClause;
64796             var hasDuplicateDefaultClause = false;
64797             var expressionType = checkExpression(node.expression);
64798             var expressionIsLiteral = isLiteralType(expressionType);
64799             ts.forEach(node.caseBlock.clauses, function (clause) {
64800                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64801                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64802                     if (firstDefaultClause === undefined) {
64803                         firstDefaultClause = clause;
64804                     }
64805                     else {
64806                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64807                         hasDuplicateDefaultClause = true;
64808                     }
64809                 }
64810                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64811                     // TypeScript 1.0 spec (April 2014): 5.9
64812                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64813                     // to or from the type of the 'switch' expression.
64814                     var caseType = checkExpression(clause.expression);
64815                     var caseIsLiteral = isLiteralType(caseType);
64816                     var comparedExpressionType = expressionType;
64817                     if (!caseIsLiteral || !expressionIsLiteral) {
64818                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
64819                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
64820                     }
64821                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
64822                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
64823                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
64824                     }
64825                 }
64826                 ts.forEach(clause.statements, checkSourceElement);
64827                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
64828                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
64829                 }
64830             });
64831             if (node.caseBlock.locals) {
64832                 registerForUnusedIdentifiersCheck(node.caseBlock);
64833             }
64834         }
64835         function checkLabeledStatement(node) {
64836             // Grammar checking
64837             if (!checkGrammarStatementInAmbientContext(node)) {
64838                 ts.findAncestor(node.parent, function (current) {
64839                     if (ts.isFunctionLike(current)) {
64840                         return "quit";
64841                     }
64842                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
64843                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
64844                         return true;
64845                     }
64846                     return false;
64847                 });
64848             }
64849             // ensure that label is unique
64850             checkSourceElement(node.statement);
64851         }
64852         function checkThrowStatement(node) {
64853             // Grammar checking
64854             if (!checkGrammarStatementInAmbientContext(node)) {
64855                 if (node.expression === undefined) {
64856                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
64857                 }
64858             }
64859             if (node.expression) {
64860                 checkExpression(node.expression);
64861             }
64862         }
64863         function checkTryStatement(node) {
64864             // Grammar checking
64865             checkGrammarStatementInAmbientContext(node);
64866             checkBlock(node.tryBlock);
64867             var catchClause = node.catchClause;
64868             if (catchClause) {
64869                 // Grammar checking
64870                 if (catchClause.variableDeclaration) {
64871                     if (catchClause.variableDeclaration.type) {
64872                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
64873                     }
64874                     else if (catchClause.variableDeclaration.initializer) {
64875                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
64876                     }
64877                     else {
64878                         var blockLocals_1 = catchClause.block.locals;
64879                         if (blockLocals_1) {
64880                             ts.forEachKey(catchClause.locals, function (caughtName) {
64881                                 var blockLocal = blockLocals_1.get(caughtName);
64882                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
64883                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
64884                                 }
64885                             });
64886                         }
64887                     }
64888                 }
64889                 checkBlock(catchClause.block);
64890             }
64891             if (node.finallyBlock) {
64892                 checkBlock(node.finallyBlock);
64893             }
64894         }
64895         function checkIndexConstraints(type) {
64896             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
64897             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
64898             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
64899             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
64900             if (stringIndexType || numberIndexType) {
64901                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
64902                     var propType = getTypeOfSymbol(prop);
64903                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64904                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64905                 });
64906                 var classDeclaration = type.symbol.valueDeclaration;
64907                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
64908                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
64909                         var member = _a[_i];
64910                         // Only process instance properties with computed names here.
64911                         // Static properties cannot be in conflict with indexers,
64912                         // and properties with literal names were already checked.
64913                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
64914                             var symbol = getSymbolOfNode(member);
64915                             var propType = getTypeOfSymbol(symbol);
64916                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64917                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64918                         }
64919                     }
64920                 }
64921             }
64922             var errorNode;
64923             if (stringIndexType && numberIndexType) {
64924                 errorNode = declaredNumberIndexer || declaredStringIndexer;
64925                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
64926                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
64927                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
64928                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
64929                 }
64930             }
64931             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
64932                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
64933             }
64934             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
64935                 // ESSymbol properties apply to neither string nor numeric indexers.
64936                 if (!indexType || ts.isKnownSymbol(prop)) {
64937                     return;
64938                 }
64939                 var propDeclaration = prop.valueDeclaration;
64940                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
64941                 if (name && ts.isPrivateIdentifier(name)) {
64942                     return;
64943                 }
64944                 // index is numeric and property name is not valid numeric literal
64945                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
64946                     return;
64947                 }
64948                 // perform property check if property or indexer is declared in 'type'
64949                 // this allows us to rule out cases when both property and indexer are inherited from the base class
64950                 var errorNode;
64951                 if (propDeclaration && name &&
64952                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
64953                         name.kind === 154 /* ComputedPropertyName */ ||
64954                         prop.parent === containingType.symbol)) {
64955                     errorNode = propDeclaration;
64956                 }
64957                 else if (indexDeclaration) {
64958                     errorNode = indexDeclaration;
64959                 }
64960                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
64961                     // for interfaces property and indexer might be inherited from different bases
64962                     // check if any base class already has both property and indexer.
64963                     // check should be performed only if 'type' is the first type that brings property\indexer together
64964                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
64965                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
64966                 }
64967                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
64968                     var errorMessage = indexKind === 0 /* String */
64969                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
64970                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
64971                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
64972                 }
64973             }
64974         }
64975         function checkTypeNameIsReserved(name, message) {
64976             // TS 1.0 spec (April 2014): 3.6.1
64977             // The predefined type keywords are reserved and cannot be used as names of user defined types.
64978             switch (name.escapedText) {
64979                 case "any":
64980                 case "unknown":
64981                 case "number":
64982                 case "bigint":
64983                 case "boolean":
64984                 case "string":
64985                 case "symbol":
64986                 case "void":
64987                 case "object":
64988                     error(name, message, name.escapedText);
64989             }
64990         }
64991         /**
64992          * The name cannot be used as 'Object' of user defined types with special target.
64993          */
64994         function checkClassNameCollisionWithObject(name) {
64995             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
64996                 && moduleKind < ts.ModuleKind.ES2015) {
64997                 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
64998             }
64999         }
65000         /**
65001          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65002          */
65003         function checkTypeParameters(typeParameterDeclarations) {
65004             if (typeParameterDeclarations) {
65005                 var seenDefault = false;
65006                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65007                     var node = typeParameterDeclarations[i];
65008                     checkTypeParameter(node);
65009                     if (produceDiagnostics) {
65010                         if (node.default) {
65011                             seenDefault = true;
65012                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65013                         }
65014                         else if (seenDefault) {
65015                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65016                         }
65017                         for (var j = 0; j < i; j++) {
65018                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65019                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65020                             }
65021                         }
65022                     }
65023                 }
65024             }
65025         }
65026         /** Check that type parameter defaults only reference previously declared type parameters */
65027         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65028             visit(root);
65029             function visit(node) {
65030                 if (node.kind === 169 /* TypeReference */) {
65031                     var type = getTypeFromTypeReference(node);
65032                     if (type.flags & 262144 /* TypeParameter */) {
65033                         for (var i = index; i < typeParameters.length; i++) {
65034                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65035                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65036                             }
65037                         }
65038                     }
65039                 }
65040                 ts.forEachChild(node, visit);
65041             }
65042         }
65043         /** Check that type parameter lists are identical across multiple declarations */
65044         function checkTypeParameterListsIdentical(symbol) {
65045             if (symbol.declarations.length === 1) {
65046                 return;
65047             }
65048             var links = getSymbolLinks(symbol);
65049             if (!links.typeParametersChecked) {
65050                 links.typeParametersChecked = true;
65051                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65052                 if (declarations.length <= 1) {
65053                     return;
65054                 }
65055                 var type = getDeclaredTypeOfSymbol(symbol);
65056                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65057                     // Report an error on every conflicting declaration.
65058                     var name = symbolToString(symbol);
65059                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65060                         var declaration = declarations_6[_i];
65061                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65062                     }
65063                 }
65064             }
65065         }
65066         function areTypeParametersIdentical(declarations, targetParameters) {
65067             var maxTypeArgumentCount = ts.length(targetParameters);
65068             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65069             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65070                 var declaration = declarations_7[_i];
65071                 // If this declaration has too few or too many type parameters, we report an error
65072                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65073                 var numTypeParameters = sourceParameters.length;
65074                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65075                     return false;
65076                 }
65077                 for (var i = 0; i < numTypeParameters; i++) {
65078                     var source = sourceParameters[i];
65079                     var target = targetParameters[i];
65080                     // If the type parameter node does not have the same as the resolved type
65081                     // parameter at this position, we report an error.
65082                     if (source.name.escapedText !== target.symbol.escapedName) {
65083                         return false;
65084                     }
65085                     // If the type parameter node does not have an identical constraint as the resolved
65086                     // type parameter at this position, we report an error.
65087                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65088                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65089                     var targetConstraint = getConstraintOfTypeParameter(target);
65090                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65091                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65092                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65093                         return false;
65094                     }
65095                     // If the type parameter node has a default and it is not identical to the default
65096                     // for the type parameter at this position, we report an error.
65097                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65098                     var targetDefault = getDefaultFromTypeParameter(target);
65099                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65100                         return false;
65101                     }
65102                 }
65103             }
65104             return true;
65105         }
65106         function checkClassExpression(node) {
65107             checkClassLikeDeclaration(node);
65108             checkNodeDeferred(node);
65109             return getTypeOfSymbol(getSymbolOfNode(node));
65110         }
65111         function checkClassExpressionDeferred(node) {
65112             ts.forEach(node.members, checkSourceElement);
65113             registerForUnusedIdentifiersCheck(node);
65114         }
65115         function checkClassDeclaration(node) {
65116             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65117                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65118             }
65119             checkClassLikeDeclaration(node);
65120             ts.forEach(node.members, checkSourceElement);
65121             registerForUnusedIdentifiersCheck(node);
65122         }
65123         function checkClassLikeDeclaration(node) {
65124             checkGrammarClassLikeDeclaration(node);
65125             checkDecorators(node);
65126             if (node.name) {
65127                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65128                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65129                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65130                 if (!(node.flags & 8388608 /* Ambient */)) {
65131                     checkClassNameCollisionWithObject(node.name);
65132                 }
65133             }
65134             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65135             checkExportsOnMergedDeclarations(node);
65136             var symbol = getSymbolOfNode(node);
65137             var type = getDeclaredTypeOfSymbol(symbol);
65138             var typeWithThis = getTypeWithThisArgument(type);
65139             var staticType = getTypeOfSymbol(symbol);
65140             checkTypeParameterListsIdentical(symbol);
65141             checkClassForDuplicateDeclarations(node);
65142             // Only check for reserved static identifiers on non-ambient context.
65143             if (!(node.flags & 8388608 /* Ambient */)) {
65144                 checkClassForStaticPropertyNameConflicts(node);
65145             }
65146             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65147             if (baseTypeNode) {
65148                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65149                 if (languageVersion < 2 /* ES2015 */) {
65150                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65151                 }
65152                 // check both @extends and extends if both are specified.
65153                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65154                 if (extendsNode && extendsNode !== baseTypeNode) {
65155                     checkExpression(extendsNode.expression);
65156                 }
65157                 var baseTypes = getBaseTypes(type);
65158                 if (baseTypes.length && produceDiagnostics) {
65159                     var baseType_1 = baseTypes[0];
65160                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65161                     var staticBaseType = getApparentType(baseConstructorType);
65162                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65163                     checkSourceElement(baseTypeNode.expression);
65164                     if (ts.some(baseTypeNode.typeArguments)) {
65165                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65166                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65167                             var constructor = _a[_i];
65168                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65169                                 break;
65170                             }
65171                         }
65172                     }
65173                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65174                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65175                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65176                     }
65177                     else {
65178                         // Report static side error only when instance type is assignable
65179                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65180                     }
65181                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65182                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65183                     }
65184                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65185                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65186                         // that all instantiated base constructor signatures return the same type.
65187                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65188                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65189                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65190                         }
65191                     }
65192                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65193                 }
65194             }
65195             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65196             if (implementedTypeNodes) {
65197                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65198                     var typeRefNode = implementedTypeNodes_1[_b];
65199                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65200                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65201                     }
65202                     checkTypeReferenceNode(typeRefNode);
65203                     if (produceDiagnostics) {
65204                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65205                         if (t !== errorType) {
65206                             if (isValidBaseType(t)) {
65207                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65208                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65209                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65210                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65211                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65212                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65213                                 }
65214                             }
65215                             else {
65216                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65217                             }
65218                         }
65219                     }
65220                 }
65221             }
65222             if (produceDiagnostics) {
65223                 checkIndexConstraints(type);
65224                 checkTypeForDuplicateIndexSignatures(node);
65225                 checkPropertyInitialization(node);
65226             }
65227         }
65228         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65229             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65230             var issuedMemberError = false;
65231             var _loop_19 = function (member) {
65232                 if (ts.hasStaticModifier(member)) {
65233                     return "continue";
65234                 }
65235                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65236                 if (declaredProp) {
65237                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65238                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65239                     if (prop && baseProp) {
65240                         var rootChain = function () { return ts.chainDiagnosticMessages(
65241                         /*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)); };
65242                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65243                             issuedMemberError = true;
65244                         }
65245                     }
65246                 }
65247             };
65248             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65249                 var member = _a[_i];
65250                 _loop_19(member);
65251             }
65252             if (!issuedMemberError) {
65253                 // check again with diagnostics to generate a less-specific error
65254                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65255             }
65256         }
65257         function checkBaseTypeAccessibility(type, node) {
65258             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65259             if (signatures.length) {
65260                 var declaration = signatures[0].declaration;
65261                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65262                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65263                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65264                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65265                     }
65266                 }
65267             }
65268         }
65269         function getTargetSymbol(s) {
65270             // if symbol is instantiated its flags are not copied from the 'target'
65271             // so we'll need to get back original 'target' symbol to work with correct set of flags
65272             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65273         }
65274         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65275             return ts.filter(symbol.declarations, function (d) {
65276                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65277             });
65278         }
65279         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65280             // TypeScript 1.0 spec (April 2014): 8.2.3
65281             // A derived class inherits all members from its base class it doesn't override.
65282             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65283             // Both public and private property members are inherited, but only public property members can be overridden.
65284             // A property member in a derived class is said to override a property member in a base class
65285             // when the derived class property member has the same name and kind(instance or static)
65286             // as the base class property member.
65287             // The type of an overriding property member must be assignable(section 3.8.4)
65288             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65289             // Base class instance member functions can be overridden by derived class instance member functions,
65290             // but not by other kinds of members.
65291             // Base class instance member variables and accessors can be overridden by
65292             // derived class instance member variables and accessors, but not by other kinds of members.
65293             // NOTE: assignability is checked in checkClassDeclaration
65294             var baseProperties = getPropertiesOfType(baseType);
65295             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65296                 var baseProperty = baseProperties_1[_i];
65297                 var base = getTargetSymbol(baseProperty);
65298                 if (base.flags & 4194304 /* Prototype */) {
65299                     continue;
65300                 }
65301                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65302                 if (!baseSymbol) {
65303                     continue;
65304                 }
65305                 var derived = getTargetSymbol(baseSymbol);
65306                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65307                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65308                 // In order to resolve whether the inherited method was overridden in the base class or not,
65309                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65310                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65311                 if (derived === base) {
65312                     // derived class inherits base without override/redeclaration
65313                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65314                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65315                     // If there is no declaration for the derived class (as in the case of class expressions),
65316                     // then the class cannot be declared abstract.
65317                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65318                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65319                         // (The class may have more than one base type via declaration merging with an interface with the
65320                         // same name.)
65321                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65322                             var otherBaseType = _b[_a];
65323                             if (otherBaseType === baseType)
65324                                 continue;
65325                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65326                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65327                             if (derivedElsewhere && derivedElsewhere !== base) {
65328                                 continue basePropertyCheck;
65329                             }
65330                         }
65331                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65332                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65333                         }
65334                         else {
65335                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65336                         }
65337                     }
65338                 }
65339                 else {
65340                     // derived overrides base.
65341                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65342                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65343                         // either base or derived property is private - not override, skip it
65344                         continue;
65345                     }
65346                     var errorMessage = void 0;
65347                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65348                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65349                     if (basePropertyFlags && derivedPropertyFlags) {
65350                         // property/accessor is overridden with property/accessor
65351                         if (!compilerOptions.useDefineForClassFields
65352                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65353                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65354                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65355                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65356                             // same when the derived property is from an assignment
65357                             continue;
65358                         }
65359                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65360                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65361                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65362                             var errorMessage_1 = overriddenInstanceProperty ?
65363                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65364                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65365                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65366                         }
65367                         else {
65368                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65369                             if (uninitialized
65370                                 && !(derived.flags & 33554432 /* Transient */)
65371                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65372                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65373                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65374                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65375                                 var propName = uninitialized.name;
65376                                 if (uninitialized.exclamationToken
65377                                     || !constructor
65378                                     || !ts.isIdentifier(propName)
65379                                     || !strictNullChecks
65380                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65381                                     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;
65382                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65383                                 }
65384                             }
65385                         }
65386                         // correct case
65387                         continue;
65388                     }
65389                     else if (isPrototypeProperty(base)) {
65390                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65391                             // method is overridden with method or property -- correct case
65392                             continue;
65393                         }
65394                         else {
65395                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65396                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65397                         }
65398                     }
65399                     else if (base.flags & 98304 /* Accessor */) {
65400                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65401                     }
65402                     else {
65403                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65404                     }
65405                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65406                 }
65407             }
65408         }
65409         function getNonInterhitedProperties(type, baseTypes, properties) {
65410             if (!ts.length(baseTypes)) {
65411                 return properties;
65412             }
65413             var seen = ts.createUnderscoreEscapedMap();
65414             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65415             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65416                 var base = baseTypes_2[_i];
65417                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65418                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65419                     var prop = properties_4[_a];
65420                     var existing = seen.get(prop.escapedName);
65421                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65422                         seen.delete(prop.escapedName);
65423                     }
65424                 }
65425             }
65426             return ts.arrayFrom(seen.values());
65427         }
65428         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65429             var baseTypes = getBaseTypes(type);
65430             if (baseTypes.length < 2) {
65431                 return true;
65432             }
65433             var seen = ts.createUnderscoreEscapedMap();
65434             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65435             var ok = true;
65436             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65437                 var base = baseTypes_3[_i];
65438                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65439                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65440                     var prop = properties_6[_a];
65441                     var existing = seen.get(prop.escapedName);
65442                     if (!existing) {
65443                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65444                     }
65445                     else {
65446                         var isInheritedProperty = existing.containingType !== type;
65447                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65448                             ok = false;
65449                             var typeName1 = typeToString(existing.containingType);
65450                             var typeName2 = typeToString(base);
65451                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65452                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65453                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65454                         }
65455                     }
65456                 }
65457             }
65458             return ok;
65459         }
65460         function checkPropertyInitialization(node) {
65461             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65462                 return;
65463             }
65464             var constructor = findConstructorDeclaration(node);
65465             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65466                 var member = _a[_i];
65467                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65468                     continue;
65469                 }
65470                 if (isInstancePropertyWithoutInitializer(member)) {
65471                     var propName = member.name;
65472                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65473                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65474                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65475                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65476                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65477                             }
65478                         }
65479                     }
65480                 }
65481             }
65482         }
65483         function isInstancePropertyWithoutInitializer(node) {
65484             return node.kind === 159 /* PropertyDeclaration */ &&
65485                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65486                 !node.exclamationToken &&
65487                 !node.initializer;
65488         }
65489         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65490             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65491             reference.expression.parent = reference;
65492             reference.parent = constructor;
65493             reference.flowNode = constructor.returnFlowNode;
65494             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65495             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65496         }
65497         function checkInterfaceDeclaration(node) {
65498             // Grammar checking
65499             if (!checkGrammarDecoratorsAndModifiers(node))
65500                 checkGrammarInterfaceDeclaration(node);
65501             checkTypeParameters(node.typeParameters);
65502             if (produceDiagnostics) {
65503                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65504                 checkExportsOnMergedDeclarations(node);
65505                 var symbol = getSymbolOfNode(node);
65506                 checkTypeParameterListsIdentical(symbol);
65507                 // Only check this symbol once
65508                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65509                 if (node === firstInterfaceDecl) {
65510                     var type = getDeclaredTypeOfSymbol(symbol);
65511                     var typeWithThis = getTypeWithThisArgument(type);
65512                     // run subsequent checks only if first set succeeded
65513                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65514                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65515                             var baseType = _a[_i];
65516                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65517                         }
65518                         checkIndexConstraints(type);
65519                     }
65520                 }
65521                 checkObjectTypeForDuplicateDeclarations(node);
65522             }
65523             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65524                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65525                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65526                 }
65527                 checkTypeReferenceNode(heritageElement);
65528             });
65529             ts.forEach(node.members, checkSourceElement);
65530             if (produceDiagnostics) {
65531                 checkTypeForDuplicateIndexSignatures(node);
65532                 registerForUnusedIdentifiersCheck(node);
65533             }
65534         }
65535         function checkTypeAliasDeclaration(node) {
65536             // Grammar checking
65537             checkGrammarDecoratorsAndModifiers(node);
65538             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65539             checkExportsOnMergedDeclarations(node);
65540             checkTypeParameters(node.typeParameters);
65541             checkSourceElement(node.type);
65542             registerForUnusedIdentifiersCheck(node);
65543         }
65544         function computeEnumMemberValues(node) {
65545             var nodeLinks = getNodeLinks(node);
65546             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65547                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65548                 var autoValue = 0;
65549                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65550                     var member = _a[_i];
65551                     var value = computeMemberValue(member, autoValue);
65552                     getNodeLinks(member).enumMemberValue = value;
65553                     autoValue = typeof value === "number" ? value + 1 : undefined;
65554                 }
65555             }
65556         }
65557         function computeMemberValue(member, autoValue) {
65558             if (ts.isComputedNonLiteralName(member.name)) {
65559                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65560             }
65561             else {
65562                 var text = ts.getTextOfPropertyName(member.name);
65563                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65564                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65565                 }
65566             }
65567             if (member.initializer) {
65568                 return computeConstantValue(member);
65569             }
65570             // In ambient non-const numeric enum declarations, enum members without initializers are
65571             // considered computed members (as opposed to having auto-incremented values).
65572             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65573                 return undefined;
65574             }
65575             // If the member declaration specifies no value, the member is considered a constant enum member.
65576             // If the member is the first member in the enum declaration, it is assigned the value zero.
65577             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65578             // occurs if the immediately preceding member is not a constant enum member.
65579             if (autoValue !== undefined) {
65580                 return autoValue;
65581             }
65582             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65583             return undefined;
65584         }
65585         function computeConstantValue(member) {
65586             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65587             var isConstEnum = ts.isEnumConst(member.parent);
65588             var initializer = member.initializer;
65589             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65590             if (value !== undefined) {
65591                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65592                     error(initializer, isNaN(value) ?
65593                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65594                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65595                 }
65596             }
65597             else if (enumKind === 1 /* Literal */) {
65598                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65599                 return 0;
65600             }
65601             else if (isConstEnum) {
65602                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65603             }
65604             else if (member.parent.flags & 8388608 /* Ambient */) {
65605                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65606             }
65607             else {
65608                 // Only here do we need to check that the initializer is assignable to the enum type.
65609                 var source = checkExpression(initializer);
65610                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65611                     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));
65612                 }
65613                 else {
65614                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65615                 }
65616             }
65617             return value;
65618             function evaluate(expr) {
65619                 switch (expr.kind) {
65620                     case 207 /* PrefixUnaryExpression */:
65621                         var value_2 = evaluate(expr.operand);
65622                         if (typeof value_2 === "number") {
65623                             switch (expr.operator) {
65624                                 case 39 /* PlusToken */: return value_2;
65625                                 case 40 /* MinusToken */: return -value_2;
65626                                 case 54 /* TildeToken */: return ~value_2;
65627                             }
65628                         }
65629                         break;
65630                     case 209 /* BinaryExpression */:
65631                         var left = evaluate(expr.left);
65632                         var right = evaluate(expr.right);
65633                         if (typeof left === "number" && typeof right === "number") {
65634                             switch (expr.operatorToken.kind) {
65635                                 case 51 /* BarToken */: return left | right;
65636                                 case 50 /* AmpersandToken */: return left & right;
65637                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65638                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65639                                 case 47 /* LessThanLessThanToken */: return left << right;
65640                                 case 52 /* CaretToken */: return left ^ right;
65641                                 case 41 /* AsteriskToken */: return left * right;
65642                                 case 43 /* SlashToken */: return left / right;
65643                                 case 39 /* PlusToken */: return left + right;
65644                                 case 40 /* MinusToken */: return left - right;
65645                                 case 44 /* PercentToken */: return left % right;
65646                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65647                             }
65648                         }
65649                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65650                             return left + right;
65651                         }
65652                         break;
65653                     case 10 /* StringLiteral */:
65654                     case 14 /* NoSubstitutionTemplateLiteral */:
65655                         return expr.text;
65656                     case 8 /* NumericLiteral */:
65657                         checkGrammarNumericLiteral(expr);
65658                         return +expr.text;
65659                     case 200 /* ParenthesizedExpression */:
65660                         return evaluate(expr.expression);
65661                     case 75 /* Identifier */:
65662                         var identifier = expr;
65663                         if (isInfinityOrNaNString(identifier.escapedText)) {
65664                             return +(identifier.escapedText);
65665                         }
65666                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65667                     case 195 /* ElementAccessExpression */:
65668                     case 194 /* PropertyAccessExpression */:
65669                         var ex = expr;
65670                         if (isConstantMemberAccess(ex)) {
65671                             var type = getTypeOfExpression(ex.expression);
65672                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65673                                 var name = void 0;
65674                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65675                                     name = ex.name.escapedText;
65676                                 }
65677                                 else {
65678                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65679                                 }
65680                                 return evaluateEnumMember(expr, type.symbol, name);
65681                             }
65682                         }
65683                         break;
65684                 }
65685                 return undefined;
65686             }
65687             function evaluateEnumMember(expr, enumSymbol, name) {
65688                 var memberSymbol = enumSymbol.exports.get(name);
65689                 if (memberSymbol) {
65690                     var declaration = memberSymbol.valueDeclaration;
65691                     if (declaration !== member) {
65692                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65693                             return getEnumMemberValue(declaration);
65694                         }
65695                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65696                         return 0;
65697                     }
65698                     else {
65699                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65700                     }
65701                 }
65702                 return undefined;
65703             }
65704         }
65705         function isConstantMemberAccess(node) {
65706             return node.kind === 75 /* Identifier */ ||
65707                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65708                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65709                     ts.isStringLiteralLike(node.argumentExpression);
65710         }
65711         function checkEnumDeclaration(node) {
65712             if (!produceDiagnostics) {
65713                 return;
65714             }
65715             // Grammar checking
65716             checkGrammarDecoratorsAndModifiers(node);
65717             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65718             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65719             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65720             checkExportsOnMergedDeclarations(node);
65721             node.members.forEach(checkEnumMember);
65722             computeEnumMemberValues(node);
65723             // Spec 2014 - Section 9.3:
65724             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65725             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65726             // for the first member.
65727             //
65728             // Only perform this check once per symbol
65729             var enumSymbol = getSymbolOfNode(node);
65730             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65731             if (node === firstDeclaration) {
65732                 if (enumSymbol.declarations.length > 1) {
65733                     var enumIsConst_1 = ts.isEnumConst(node);
65734                     // check that const is placed\omitted on all enum declarations
65735                     ts.forEach(enumSymbol.declarations, function (decl) {
65736                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65737                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65738                         }
65739                     });
65740                 }
65741                 var seenEnumMissingInitialInitializer_1 = false;
65742                 ts.forEach(enumSymbol.declarations, function (declaration) {
65743                     // return true if we hit a violation of the rule, false otherwise
65744                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65745                         return false;
65746                     }
65747                     var enumDeclaration = declaration;
65748                     if (!enumDeclaration.members.length) {
65749                         return false;
65750                     }
65751                     var firstEnumMember = enumDeclaration.members[0];
65752                     if (!firstEnumMember.initializer) {
65753                         if (seenEnumMissingInitialInitializer_1) {
65754                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65755                         }
65756                         else {
65757                             seenEnumMissingInitialInitializer_1 = true;
65758                         }
65759                     }
65760                 });
65761             }
65762         }
65763         function checkEnumMember(node) {
65764             if (ts.isPrivateIdentifier(node.name)) {
65765                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65766             }
65767         }
65768         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65769             var declarations = symbol.declarations;
65770             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65771                 var declaration = declarations_8[_i];
65772                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65773                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65774                     !(declaration.flags & 8388608 /* Ambient */)) {
65775                     return declaration;
65776                 }
65777             }
65778             return undefined;
65779         }
65780         function inSameLexicalScope(node1, node2) {
65781             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65782             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65783             if (isGlobalSourceFile(container1)) {
65784                 return isGlobalSourceFile(container2);
65785             }
65786             else if (isGlobalSourceFile(container2)) {
65787                 return false;
65788             }
65789             else {
65790                 return container1 === container2;
65791             }
65792         }
65793         function checkModuleDeclaration(node) {
65794             if (produceDiagnostics) {
65795                 // Grammar checking
65796                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65797                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65798                 if (isGlobalAugmentation && !inAmbientContext) {
65799                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65800                 }
65801                 var isAmbientExternalModule = ts.isAmbientModule(node);
65802                 var contextErrorMessage = isAmbientExternalModule
65803                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65804                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65805                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65806                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65807                     return;
65808                 }
65809                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65810                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65811                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65812                     }
65813                 }
65814                 if (ts.isIdentifier(node.name)) {
65815                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65816                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65817                 }
65818                 checkExportsOnMergedDeclarations(node);
65819                 var symbol = getSymbolOfNode(node);
65820                 // The following checks only apply on a non-ambient instantiated module declaration.
65821                 if (symbol.flags & 512 /* ValueModule */
65822                     && !inAmbientContext
65823                     && symbol.declarations.length > 1
65824                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
65825                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
65826                     if (firstNonAmbientClassOrFunc) {
65827                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
65828                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
65829                         }
65830                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
65831                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
65832                         }
65833                     }
65834                     // if the module merges with a class declaration in the same lexical scope,
65835                     // we need to track this to ensure the correct emit.
65836                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
65837                     if (mergedClass &&
65838                         inSameLexicalScope(node, mergedClass)) {
65839                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
65840                     }
65841                 }
65842                 if (isAmbientExternalModule) {
65843                     if (ts.isExternalModuleAugmentation(node)) {
65844                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
65845                         // otherwise we'll be swamped in cascading errors.
65846                         // We can detect if augmentation was applied using following rules:
65847                         // - augmentation for a global scope is always applied
65848                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
65849                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
65850                         if (checkBody && node.body) {
65851                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
65852                                 var statement = _a[_i];
65853                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
65854                             }
65855                         }
65856                     }
65857                     else if (isGlobalSourceFile(node.parent)) {
65858                         if (isGlobalAugmentation) {
65859                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65860                         }
65861                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
65862                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
65863                         }
65864                     }
65865                     else {
65866                         if (isGlobalAugmentation) {
65867                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65868                         }
65869                         else {
65870                             // Node is not an augmentation and is not located on the script level.
65871                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
65872                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
65873                         }
65874                     }
65875                 }
65876             }
65877             if (node.body) {
65878                 checkSourceElement(node.body);
65879                 if (!ts.isGlobalScopeAugmentation(node)) {
65880                     registerForUnusedIdentifiersCheck(node);
65881                 }
65882             }
65883         }
65884         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
65885             switch (node.kind) {
65886                 case 225 /* VariableStatement */:
65887                     // error each individual name in variable statement instead of marking the entire variable statement
65888                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
65889                         var decl = _a[_i];
65890                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
65891                     }
65892                     break;
65893                 case 259 /* ExportAssignment */:
65894                 case 260 /* ExportDeclaration */:
65895                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
65896                     break;
65897                 case 253 /* ImportEqualsDeclaration */:
65898                 case 254 /* ImportDeclaration */:
65899                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
65900                     break;
65901                 case 191 /* BindingElement */:
65902                 case 242 /* VariableDeclaration */:
65903                     var name = node.name;
65904                     if (ts.isBindingPattern(name)) {
65905                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
65906                             var el = _c[_b];
65907                             // mark individual names in binding pattern
65908                             checkModuleAugmentationElement(el, isGlobalAugmentation);
65909                         }
65910                         break;
65911                     }
65912                 // falls through
65913                 case 245 /* ClassDeclaration */:
65914                 case 248 /* EnumDeclaration */:
65915                 case 244 /* FunctionDeclaration */:
65916                 case 246 /* InterfaceDeclaration */:
65917                 case 249 /* ModuleDeclaration */:
65918                 case 247 /* TypeAliasDeclaration */:
65919                     if (isGlobalAugmentation) {
65920                         return;
65921                     }
65922                     var symbol = getSymbolOfNode(node);
65923                     if (symbol) {
65924                         // module augmentations cannot introduce new names on the top level scope of the module
65925                         // this is done it two steps
65926                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
65927                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
65928                         var reportError = !(symbol.flags & 33554432 /* Transient */);
65929                         if (!reportError) {
65930                             // symbol should not originate in augmentation
65931                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
65932                         }
65933                     }
65934                     break;
65935             }
65936         }
65937         function getFirstNonModuleExportsIdentifier(node) {
65938             switch (node.kind) {
65939                 case 75 /* Identifier */:
65940                     return node;
65941                 case 153 /* QualifiedName */:
65942                     do {
65943                         node = node.left;
65944                     } while (node.kind !== 75 /* Identifier */);
65945                     return node;
65946                 case 194 /* PropertyAccessExpression */:
65947                     do {
65948                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
65949                             return node.name;
65950                         }
65951                         node = node.expression;
65952                     } while (node.kind !== 75 /* Identifier */);
65953                     return node;
65954             }
65955         }
65956         function checkExternalImportOrExportDeclaration(node) {
65957             var moduleName = ts.getExternalModuleName(node);
65958             if (!moduleName || ts.nodeIsMissing(moduleName)) {
65959                 // Should be a parse error.
65960                 return false;
65961             }
65962             if (!ts.isStringLiteral(moduleName)) {
65963                 error(moduleName, ts.Diagnostics.String_literal_expected);
65964                 return false;
65965             }
65966             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
65967             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
65968                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
65969                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
65970                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
65971                 return false;
65972             }
65973             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
65974                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
65975                 // no need to do this again.
65976                 if (!isTopLevelInExternalModuleAugmentation(node)) {
65977                     // TypeScript 1.0 spec (April 2013): 12.1.6
65978                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
65979                     // other external modules only through top - level external module names.
65980                     // Relative external module names are not permitted.
65981                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
65982                     return false;
65983                 }
65984             }
65985             return true;
65986         }
65987         function checkAliasSymbol(node) {
65988             var symbol = getSymbolOfNode(node);
65989             var target = resolveAlias(symbol);
65990             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
65991             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
65992                 // For external modules symbol represents local symbol for an alias.
65993                 // This local symbol will merge any other local declarations (excluding other aliases)
65994                 // and symbol.flags will contains combined representation for all merged declaration.
65995                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
65996                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
65997                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
65998                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
65999                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66000                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66001                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66002                 if (target.flags & excludedMeanings) {
66003                     var message = node.kind === 263 /* ExportSpecifier */ ?
66004                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66005                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66006                     error(node, message, symbolToString(symbol));
66007                 }
66008                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66009                 if (compilerOptions.isolatedModules
66010                     && node.kind === 263 /* ExportSpecifier */
66011                     && !node.parent.parent.isTypeOnly
66012                     && !(target.flags & 111551 /* Value */)
66013                     && !(node.flags & 8388608 /* Ambient */)) {
66014                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66015                 }
66016             }
66017         }
66018         function checkImportBinding(node) {
66019             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66020             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66021             checkAliasSymbol(node);
66022         }
66023         function checkImportDeclaration(node) {
66024             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66025                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66026                 return;
66027             }
66028             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66029                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66030             }
66031             if (checkExternalImportOrExportDeclaration(node)) {
66032                 var importClause = node.importClause;
66033                 if (importClause && !checkGrammarImportClause(importClause)) {
66034                     if (importClause.name) {
66035                         checkImportBinding(importClause);
66036                     }
66037                     if (importClause.namedBindings) {
66038                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66039                             checkImportBinding(importClause.namedBindings);
66040                         }
66041                         else {
66042                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66043                             if (moduleExisted) {
66044                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66045                             }
66046                         }
66047                     }
66048                 }
66049             }
66050         }
66051         function checkImportEqualsDeclaration(node) {
66052             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66053                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66054                 return;
66055             }
66056             checkGrammarDecoratorsAndModifiers(node);
66057             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66058                 checkImportBinding(node);
66059                 if (ts.hasModifier(node, 1 /* Export */)) {
66060                     markExportAsReferenced(node);
66061                 }
66062                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66063                     var target = resolveAlias(getSymbolOfNode(node));
66064                     if (target !== unknownSymbol) {
66065                         if (target.flags & 111551 /* Value */) {
66066                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66067                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66068                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66069                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66070                             }
66071                         }
66072                         if (target.flags & 788968 /* Type */) {
66073                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66074                         }
66075                     }
66076                 }
66077                 else {
66078                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66079                         // Import equals declaration is deprecated in es6 or above
66080                         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);
66081                     }
66082                 }
66083             }
66084         }
66085         function checkExportDeclaration(node) {
66086             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66087                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66088                 return;
66089             }
66090             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66091                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66092             }
66093             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66094                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66095             }
66096             checkGrammarExportDeclaration(node);
66097             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66098                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66099                     // export { x, y }
66100                     // export { x, y } from "foo"
66101                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66102                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66103                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66104                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66105                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66106                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66107                     }
66108                 }
66109                 else {
66110                     // export * from "foo"
66111                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66112                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66113                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66114                     }
66115                     else if (node.exportClause) {
66116                         checkAliasSymbol(node.exportClause);
66117                     }
66118                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66119                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66120                     }
66121                 }
66122             }
66123         }
66124         function checkGrammarExportDeclaration(node) {
66125             var _a;
66126             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66127             if (isTypeOnlyExportStar) {
66128                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66129             }
66130             return !isTypeOnlyExportStar;
66131         }
66132         function checkGrammarModuleElementContext(node, errorMessage) {
66133             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66134             if (!isInAppropriateContext) {
66135                 grammarErrorOnFirstToken(node, errorMessage);
66136             }
66137             return !isInAppropriateContext;
66138         }
66139         function importClauseContainsReferencedImport(importClause) {
66140             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66141                 return !!getSymbolOfNode(declaration).isReferenced;
66142             });
66143         }
66144         function importClauseContainsConstEnumUsedAsValue(importClause) {
66145             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66146                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66147             });
66148         }
66149         function checkImportsForTypeOnlyConversion(sourceFile) {
66150             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66151                 var statement = _a[_i];
66152                 if (ts.isImportDeclaration(statement) &&
66153                     statement.importClause &&
66154                     !statement.importClause.isTypeOnly &&
66155                     importClauseContainsReferencedImport(statement.importClause) &&
66156                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66157                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66158                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66159                 }
66160             }
66161         }
66162         function checkExportSpecifier(node) {
66163             checkAliasSymbol(node);
66164             if (ts.getEmitDeclarations(compilerOptions)) {
66165                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66166             }
66167             if (!node.parent.parent.moduleSpecifier) {
66168                 var exportedName = node.propertyName || node.name;
66169                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66170                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66171                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66172                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66173                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66174                 }
66175                 else {
66176                     markExportAsReferenced(node);
66177                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66178                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66179                         checkExpressionCached(node.propertyName || node.name);
66180                     }
66181                 }
66182             }
66183         }
66184         function checkExportAssignment(node) {
66185             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66186                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66187                 return;
66188             }
66189             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66190             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66191                 if (node.isExportEquals) {
66192                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66193                 }
66194                 else {
66195                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66196                 }
66197                 return;
66198             }
66199             // Grammar checking
66200             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66201                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66202             }
66203             if (node.expression.kind === 75 /* Identifier */) {
66204                 var id = node.expression;
66205                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66206                 if (sym) {
66207                     markAliasReferenced(sym, id);
66208                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66209                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66210                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66211                         // However if it is a value, we need to check it's being used correctly
66212                         checkExpressionCached(node.expression);
66213                     }
66214                 }
66215                 if (ts.getEmitDeclarations(compilerOptions)) {
66216                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66217                 }
66218             }
66219             else {
66220                 checkExpressionCached(node.expression);
66221             }
66222             checkExternalModuleExports(container);
66223             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66224                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66225             }
66226             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66227                 if (moduleKind >= ts.ModuleKind.ES2015) {
66228                     // export assignment is not supported in es6 modules
66229                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66230                 }
66231                 else if (moduleKind === ts.ModuleKind.System) {
66232                     // system modules does not support export assignment
66233                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66234                 }
66235             }
66236         }
66237         function hasExportedMembers(moduleSymbol) {
66238             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66239         }
66240         function checkExternalModuleExports(node) {
66241             var moduleSymbol = getSymbolOfNode(node);
66242             var links = getSymbolLinks(moduleSymbol);
66243             if (!links.exportsChecked) {
66244                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66245                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66246                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66247                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66248                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66249                     }
66250                 }
66251                 // Checks for export * conflicts
66252                 var exports_2 = getExportsOfModule(moduleSymbol);
66253                 if (exports_2) {
66254                     exports_2.forEach(function (_a, id) {
66255                         var declarations = _a.declarations, flags = _a.flags;
66256                         if (id === "__export") {
66257                             return;
66258                         }
66259                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66260                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66261                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66262                             return;
66263                         }
66264                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66265                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66266                             // it is legal to merge type alias with other values
66267                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66268                             return;
66269                         }
66270                         if (exportedDeclarationsCount > 1) {
66271                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66272                                 var declaration = declarations_9[_i];
66273                                 if (isNotOverload(declaration)) {
66274                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66275                                 }
66276                             }
66277                         }
66278                     });
66279                 }
66280                 links.exportsChecked = true;
66281             }
66282         }
66283         function checkSourceElement(node) {
66284             if (node) {
66285                 var saveCurrentNode = currentNode;
66286                 currentNode = node;
66287                 instantiationCount = 0;
66288                 checkSourceElementWorker(node);
66289                 currentNode = saveCurrentNode;
66290             }
66291         }
66292         function checkSourceElementWorker(node) {
66293             if (ts.isInJSFile(node)) {
66294                 ts.forEach(node.jsDoc, function (_a) {
66295                     var tags = _a.tags;
66296                     return ts.forEach(tags, checkSourceElement);
66297                 });
66298             }
66299             var kind = node.kind;
66300             if (cancellationToken) {
66301                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66302                 // hitting the cancellation token on every node we check.
66303                 switch (kind) {
66304                     case 249 /* ModuleDeclaration */:
66305                     case 245 /* ClassDeclaration */:
66306                     case 246 /* InterfaceDeclaration */:
66307                     case 244 /* FunctionDeclaration */:
66308                         cancellationToken.throwIfCancellationRequested();
66309                 }
66310             }
66311             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66312                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66313             }
66314             switch (kind) {
66315                 case 155 /* TypeParameter */:
66316                     return checkTypeParameter(node);
66317                 case 156 /* Parameter */:
66318                     return checkParameter(node);
66319                 case 159 /* PropertyDeclaration */:
66320                     return checkPropertyDeclaration(node);
66321                 case 158 /* PropertySignature */:
66322                     return checkPropertySignature(node);
66323                 case 170 /* FunctionType */:
66324                 case 171 /* ConstructorType */:
66325                 case 165 /* CallSignature */:
66326                 case 166 /* ConstructSignature */:
66327                 case 167 /* IndexSignature */:
66328                     return checkSignatureDeclaration(node);
66329                 case 161 /* MethodDeclaration */:
66330                 case 160 /* MethodSignature */:
66331                     return checkMethodDeclaration(node);
66332                 case 162 /* Constructor */:
66333                     return checkConstructorDeclaration(node);
66334                 case 163 /* GetAccessor */:
66335                 case 164 /* SetAccessor */:
66336                     return checkAccessorDeclaration(node);
66337                 case 169 /* TypeReference */:
66338                     return checkTypeReferenceNode(node);
66339                 case 168 /* TypePredicate */:
66340                     return checkTypePredicate(node);
66341                 case 172 /* TypeQuery */:
66342                     return checkTypeQuery(node);
66343                 case 173 /* TypeLiteral */:
66344                     return checkTypeLiteral(node);
66345                 case 174 /* ArrayType */:
66346                     return checkArrayType(node);
66347                 case 175 /* TupleType */:
66348                     return checkTupleType(node);
66349                 case 178 /* UnionType */:
66350                 case 179 /* IntersectionType */:
66351                     return checkUnionOrIntersectionType(node);
66352                 case 182 /* ParenthesizedType */:
66353                 case 176 /* OptionalType */:
66354                 case 177 /* RestType */:
66355                     return checkSourceElement(node.type);
66356                 case 183 /* ThisType */:
66357                     return checkThisType(node);
66358                 case 184 /* TypeOperator */:
66359                     return checkTypeOperator(node);
66360                 case 180 /* ConditionalType */:
66361                     return checkConditionalType(node);
66362                 case 181 /* InferType */:
66363                     return checkInferType(node);
66364                 case 188 /* ImportType */:
66365                     return checkImportType(node);
66366                 case 307 /* JSDocAugmentsTag */:
66367                     return checkJSDocAugmentsTag(node);
66368                 case 308 /* JSDocImplementsTag */:
66369                     return checkJSDocImplementsTag(node);
66370                 case 322 /* JSDocTypedefTag */:
66371                 case 315 /* JSDocCallbackTag */:
66372                 case 316 /* JSDocEnumTag */:
66373                     return checkJSDocTypeAliasTag(node);
66374                 case 321 /* JSDocTemplateTag */:
66375                     return checkJSDocTemplateTag(node);
66376                 case 320 /* JSDocTypeTag */:
66377                     return checkJSDocTypeTag(node);
66378                 case 317 /* JSDocParameterTag */:
66379                     return checkJSDocParameterTag(node);
66380                 case 323 /* JSDocPropertyTag */:
66381                     return checkJSDocPropertyTag(node);
66382                 case 300 /* JSDocFunctionType */:
66383                     checkJSDocFunctionType(node);
66384                 // falls through
66385                 case 298 /* JSDocNonNullableType */:
66386                 case 297 /* JSDocNullableType */:
66387                 case 295 /* JSDocAllType */:
66388                 case 296 /* JSDocUnknownType */:
66389                 case 304 /* JSDocTypeLiteral */:
66390                     checkJSDocTypeIsInJsFile(node);
66391                     ts.forEachChild(node, checkSourceElement);
66392                     return;
66393                 case 301 /* JSDocVariadicType */:
66394                     checkJSDocVariadicType(node);
66395                     return;
66396                 case 294 /* JSDocTypeExpression */:
66397                     return checkSourceElement(node.type);
66398                 case 185 /* IndexedAccessType */:
66399                     return checkIndexedAccessType(node);
66400                 case 186 /* MappedType */:
66401                     return checkMappedType(node);
66402                 case 244 /* FunctionDeclaration */:
66403                     return checkFunctionDeclaration(node);
66404                 case 223 /* Block */:
66405                 case 250 /* ModuleBlock */:
66406                     return checkBlock(node);
66407                 case 225 /* VariableStatement */:
66408                     return checkVariableStatement(node);
66409                 case 226 /* ExpressionStatement */:
66410                     return checkExpressionStatement(node);
66411                 case 227 /* IfStatement */:
66412                     return checkIfStatement(node);
66413                 case 228 /* DoStatement */:
66414                     return checkDoStatement(node);
66415                 case 229 /* WhileStatement */:
66416                     return checkWhileStatement(node);
66417                 case 230 /* ForStatement */:
66418                     return checkForStatement(node);
66419                 case 231 /* ForInStatement */:
66420                     return checkForInStatement(node);
66421                 case 232 /* ForOfStatement */:
66422                     return checkForOfStatement(node);
66423                 case 233 /* ContinueStatement */:
66424                 case 234 /* BreakStatement */:
66425                     return checkBreakOrContinueStatement(node);
66426                 case 235 /* ReturnStatement */:
66427                     return checkReturnStatement(node);
66428                 case 236 /* WithStatement */:
66429                     return checkWithStatement(node);
66430                 case 237 /* SwitchStatement */:
66431                     return checkSwitchStatement(node);
66432                 case 238 /* LabeledStatement */:
66433                     return checkLabeledStatement(node);
66434                 case 239 /* ThrowStatement */:
66435                     return checkThrowStatement(node);
66436                 case 240 /* TryStatement */:
66437                     return checkTryStatement(node);
66438                 case 242 /* VariableDeclaration */:
66439                     return checkVariableDeclaration(node);
66440                 case 191 /* BindingElement */:
66441                     return checkBindingElement(node);
66442                 case 245 /* ClassDeclaration */:
66443                     return checkClassDeclaration(node);
66444                 case 246 /* InterfaceDeclaration */:
66445                     return checkInterfaceDeclaration(node);
66446                 case 247 /* TypeAliasDeclaration */:
66447                     return checkTypeAliasDeclaration(node);
66448                 case 248 /* EnumDeclaration */:
66449                     return checkEnumDeclaration(node);
66450                 case 249 /* ModuleDeclaration */:
66451                     return checkModuleDeclaration(node);
66452                 case 254 /* ImportDeclaration */:
66453                     return checkImportDeclaration(node);
66454                 case 253 /* ImportEqualsDeclaration */:
66455                     return checkImportEqualsDeclaration(node);
66456                 case 260 /* ExportDeclaration */:
66457                     return checkExportDeclaration(node);
66458                 case 259 /* ExportAssignment */:
66459                     return checkExportAssignment(node);
66460                 case 224 /* EmptyStatement */:
66461                 case 241 /* DebuggerStatement */:
66462                     checkGrammarStatementInAmbientContext(node);
66463                     return;
66464                 case 264 /* MissingDeclaration */:
66465                     return checkMissingDeclaration(node);
66466             }
66467         }
66468         function checkJSDocTypeIsInJsFile(node) {
66469             if (!ts.isInJSFile(node)) {
66470                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66471             }
66472         }
66473         function checkJSDocVariadicType(node) {
66474             checkJSDocTypeIsInJsFile(node);
66475             checkSourceElement(node.type);
66476             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66477             var parent = node.parent;
66478             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66479                 if (ts.last(parent.parent.parameters) !== parent) {
66480                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66481                 }
66482                 return;
66483             }
66484             if (!ts.isJSDocTypeExpression(parent)) {
66485                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66486             }
66487             var paramTag = node.parent.parent;
66488             if (!ts.isJSDocParameterTag(paramTag)) {
66489                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66490                 return;
66491             }
66492             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66493             if (!param) {
66494                 // We will error in `checkJSDocParameterTag`.
66495                 return;
66496             }
66497             var host = ts.getHostSignatureFromJSDoc(paramTag);
66498             if (!host || ts.last(host.parameters).symbol !== param) {
66499                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66500             }
66501         }
66502         function getTypeFromJSDocVariadicType(node) {
66503             var type = getTypeFromTypeNode(node.type);
66504             var parent = node.parent;
66505             var paramTag = node.parent.parent;
66506             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66507                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66508                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66509                 if (host_1) {
66510                     /*
66511                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66512                     So in the following situation we will not create an array type:
66513                         /** @param {...number} a * /
66514                         function f(a) {}
66515                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66516                     */
66517                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66518                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66519                     if (!lastParamDeclaration ||
66520                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66521                         return createArrayType(type);
66522                     }
66523                 }
66524             }
66525             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66526                 return createArrayType(type);
66527             }
66528             return addOptionality(type);
66529         }
66530         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66531         // to ensure constructs like the following are permitted:
66532         //     const foo = function () {
66533         //        const s = foo();
66534         //        return "hello";
66535         //     }
66536         // Here, performing a full type check of the body of the function expression whilst in the process of
66537         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66538         // Delaying the type check of the body ensures foo has been assigned a type.
66539         function checkNodeDeferred(node) {
66540             var enclosingFile = ts.getSourceFileOfNode(node);
66541             var links = getNodeLinks(enclosingFile);
66542             if (!(links.flags & 1 /* TypeChecked */)) {
66543                 links.deferredNodes = links.deferredNodes || ts.createMap();
66544                 var id = "" + getNodeId(node);
66545                 links.deferredNodes.set(id, node);
66546             }
66547         }
66548         function checkDeferredNodes(context) {
66549             var links = getNodeLinks(context);
66550             if (links.deferredNodes) {
66551                 links.deferredNodes.forEach(checkDeferredNode);
66552             }
66553         }
66554         function checkDeferredNode(node) {
66555             var saveCurrentNode = currentNode;
66556             currentNode = node;
66557             instantiationCount = 0;
66558             switch (node.kind) {
66559                 case 196 /* CallExpression */:
66560                 case 197 /* NewExpression */:
66561                 case 198 /* TaggedTemplateExpression */:
66562                 case 157 /* Decorator */:
66563                 case 268 /* JsxOpeningElement */:
66564                     // These node kinds are deferred checked when overload resolution fails
66565                     // To save on work, we ensure the arguments are checked just once, in
66566                     // a deferred way
66567                     resolveUntypedCall(node);
66568                     break;
66569                 case 201 /* FunctionExpression */:
66570                 case 202 /* ArrowFunction */:
66571                 case 161 /* MethodDeclaration */:
66572                 case 160 /* MethodSignature */:
66573                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66574                     break;
66575                 case 163 /* GetAccessor */:
66576                 case 164 /* SetAccessor */:
66577                     checkAccessorDeclaration(node);
66578                     break;
66579                 case 214 /* ClassExpression */:
66580                     checkClassExpressionDeferred(node);
66581                     break;
66582                 case 267 /* JsxSelfClosingElement */:
66583                     checkJsxSelfClosingElementDeferred(node);
66584                     break;
66585                 case 266 /* JsxElement */:
66586                     checkJsxElementDeferred(node);
66587                     break;
66588             }
66589             currentNode = saveCurrentNode;
66590         }
66591         function checkSourceFile(node) {
66592             ts.performance.mark("beforeCheck");
66593             checkSourceFileWorker(node);
66594             ts.performance.mark("afterCheck");
66595             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66596         }
66597         function unusedIsError(kind, isAmbient) {
66598             if (isAmbient) {
66599                 return false;
66600             }
66601             switch (kind) {
66602                 case 0 /* Local */:
66603                     return !!compilerOptions.noUnusedLocals;
66604                 case 1 /* Parameter */:
66605                     return !!compilerOptions.noUnusedParameters;
66606                 default:
66607                     return ts.Debug.assertNever(kind);
66608             }
66609         }
66610         function getPotentiallyUnusedIdentifiers(sourceFile) {
66611             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66612         }
66613         // Fully type check a source file and collect the relevant diagnostics.
66614         function checkSourceFileWorker(node) {
66615             var links = getNodeLinks(node);
66616             if (!(links.flags & 1 /* TypeChecked */)) {
66617                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66618                     return;
66619                 }
66620                 // Grammar checking
66621                 checkGrammarSourceFile(node);
66622                 ts.clear(potentialThisCollisions);
66623                 ts.clear(potentialNewTargetCollisions);
66624                 ts.clear(potentialWeakMapCollisions);
66625                 ts.forEach(node.statements, checkSourceElement);
66626                 checkSourceElement(node.endOfFileToken);
66627                 checkDeferredNodes(node);
66628                 if (ts.isExternalOrCommonJsModule(node)) {
66629                     registerForUnusedIdentifiersCheck(node);
66630                 }
66631                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66632                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66633                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66634                             diagnostics.add(diag);
66635                         }
66636                     });
66637                 }
66638                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66639                     !node.isDeclarationFile &&
66640                     ts.isExternalModule(node)) {
66641                     checkImportsForTypeOnlyConversion(node);
66642                 }
66643                 if (ts.isExternalOrCommonJsModule(node)) {
66644                     checkExternalModuleExports(node);
66645                 }
66646                 if (potentialThisCollisions.length) {
66647                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66648                     ts.clear(potentialThisCollisions);
66649                 }
66650                 if (potentialNewTargetCollisions.length) {
66651                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66652                     ts.clear(potentialNewTargetCollisions);
66653                 }
66654                 if (potentialWeakMapCollisions.length) {
66655                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66656                     ts.clear(potentialWeakMapCollisions);
66657                 }
66658                 links.flags |= 1 /* TypeChecked */;
66659             }
66660         }
66661         function getDiagnostics(sourceFile, ct) {
66662             try {
66663                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66664                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66665                 // this call is done.
66666                 cancellationToken = ct;
66667                 return getDiagnosticsWorker(sourceFile);
66668             }
66669             finally {
66670                 cancellationToken = undefined;
66671             }
66672         }
66673         function getDiagnosticsWorker(sourceFile) {
66674             throwIfNonDiagnosticsProducing();
66675             if (sourceFile) {
66676                 // Some global diagnostics are deferred until they are needed and
66677                 // may not be reported in the first call to getGlobalDiagnostics.
66678                 // We should catch these changes and report them.
66679                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66680                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66681                 checkSourceFile(sourceFile);
66682                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66683                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66684                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66685                     // If the arrays are not the same reference, new diagnostics were added.
66686                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66687                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66688                 }
66689                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66690                     // If the arrays are the same reference, but the length has changed, a single
66691                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66692                     // same array.
66693                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66694                 }
66695                 return semanticDiagnostics;
66696             }
66697             // Global diagnostics are always added when a file is not provided to
66698             // getDiagnostics
66699             ts.forEach(host.getSourceFiles(), checkSourceFile);
66700             return diagnostics.getDiagnostics();
66701         }
66702         function getGlobalDiagnostics() {
66703             throwIfNonDiagnosticsProducing();
66704             return diagnostics.getGlobalDiagnostics();
66705         }
66706         function throwIfNonDiagnosticsProducing() {
66707             if (!produceDiagnostics) {
66708                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66709             }
66710         }
66711         // Language service support
66712         function getSymbolsInScope(location, meaning) {
66713             if (location.flags & 16777216 /* InWithStatement */) {
66714                 // We cannot answer semantic questions within a with block, do not proceed any further
66715                 return [];
66716             }
66717             var symbols = ts.createSymbolTable();
66718             var isStatic = false;
66719             populateSymbols();
66720             symbols.delete("this" /* This */); // Not a symbol, a keyword
66721             return symbolsToArray(symbols);
66722             function populateSymbols() {
66723                 while (location) {
66724                     if (location.locals && !isGlobalSourceFile(location)) {
66725                         copySymbols(location.locals, meaning);
66726                     }
66727                     switch (location.kind) {
66728                         case 290 /* SourceFile */:
66729                             if (!ts.isExternalOrCommonJsModule(location))
66730                                 break;
66731                         // falls through
66732                         case 249 /* ModuleDeclaration */:
66733                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66734                             break;
66735                         case 248 /* EnumDeclaration */:
66736                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66737                             break;
66738                         case 214 /* ClassExpression */:
66739                             var className = location.name;
66740                             if (className) {
66741                                 copySymbol(location.symbol, meaning);
66742                             }
66743                         // this fall-through is necessary because we would like to handle
66744                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66745                         // falls through
66746                         case 245 /* ClassDeclaration */:
66747                         case 246 /* InterfaceDeclaration */:
66748                             // If we didn't come from static member of class or interface,
66749                             // add the type parameters into the symbol table
66750                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66751                             // Note: that the memberFlags come from previous iteration.
66752                             if (!isStatic) {
66753                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66754                             }
66755                             break;
66756                         case 201 /* FunctionExpression */:
66757                             var funcName = location.name;
66758                             if (funcName) {
66759                                 copySymbol(location.symbol, meaning);
66760                             }
66761                             break;
66762                     }
66763                     if (ts.introducesArgumentsExoticObject(location)) {
66764                         copySymbol(argumentsSymbol, meaning);
66765                     }
66766                     isStatic = ts.hasModifier(location, 32 /* Static */);
66767                     location = location.parent;
66768                 }
66769                 copySymbols(globals, meaning);
66770             }
66771             /**
66772              * Copy the given symbol into symbol tables if the symbol has the given meaning
66773              * and it doesn't already existed in the symbol table
66774              * @param key a key for storing in symbol table; if undefined, use symbol.name
66775              * @param symbol the symbol to be added into symbol table
66776              * @param meaning meaning of symbol to filter by before adding to symbol table
66777              */
66778             function copySymbol(symbol, meaning) {
66779                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66780                     var id = symbol.escapedName;
66781                     // We will copy all symbol regardless of its reserved name because
66782                     // symbolsToArray will check whether the key is a reserved name and
66783                     // it will not copy symbol with reserved name to the array
66784                     if (!symbols.has(id)) {
66785                         symbols.set(id, symbol);
66786                     }
66787                 }
66788             }
66789             function copySymbols(source, meaning) {
66790                 if (meaning) {
66791                     source.forEach(function (symbol) {
66792                         copySymbol(symbol, meaning);
66793                     });
66794                 }
66795             }
66796         }
66797         function isTypeDeclarationName(name) {
66798             return name.kind === 75 /* Identifier */ &&
66799                 isTypeDeclaration(name.parent) &&
66800                 name.parent.name === name;
66801         }
66802         function isTypeDeclaration(node) {
66803             switch (node.kind) {
66804                 case 155 /* TypeParameter */:
66805                 case 245 /* ClassDeclaration */:
66806                 case 246 /* InterfaceDeclaration */:
66807                 case 247 /* TypeAliasDeclaration */:
66808                 case 248 /* EnumDeclaration */:
66809                     return true;
66810                 case 255 /* ImportClause */:
66811                     return node.isTypeOnly;
66812                 case 258 /* ImportSpecifier */:
66813                 case 263 /* ExportSpecifier */:
66814                     return node.parent.parent.isTypeOnly;
66815                 default:
66816                     return false;
66817             }
66818         }
66819         // True if the given identifier is part of a type reference
66820         function isTypeReferenceIdentifier(node) {
66821             while (node.parent.kind === 153 /* QualifiedName */) {
66822                 node = node.parent;
66823             }
66824             return node.parent.kind === 169 /* TypeReference */;
66825         }
66826         function isHeritageClauseElementIdentifier(node) {
66827             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
66828                 node = node.parent;
66829             }
66830             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
66831         }
66832         function forEachEnclosingClass(node, callback) {
66833             var result;
66834             while (true) {
66835                 node = ts.getContainingClass(node);
66836                 if (!node)
66837                     break;
66838                 if (result = callback(node))
66839                     break;
66840             }
66841             return result;
66842         }
66843         function isNodeUsedDuringClassInitialization(node) {
66844             return !!ts.findAncestor(node, function (element) {
66845                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
66846                     return true;
66847                 }
66848                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
66849                     return "quit";
66850                 }
66851                 return false;
66852             });
66853         }
66854         function isNodeWithinClass(node, classDeclaration) {
66855             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
66856         }
66857         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
66858             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
66859                 nodeOnRightSide = nodeOnRightSide.parent;
66860             }
66861             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
66862                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66863             }
66864             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
66865                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66866             }
66867             return undefined;
66868         }
66869         function isInRightSideOfImportOrExportAssignment(node) {
66870             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
66871         }
66872         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
66873             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
66874             switch (specialPropertyAssignmentKind) {
66875                 case 1 /* ExportsProperty */:
66876                 case 3 /* PrototypeProperty */:
66877                     return getSymbolOfNode(entityName.parent);
66878                 case 4 /* ThisProperty */:
66879                 case 2 /* ModuleExports */:
66880                 case 5 /* Property */:
66881                     return getSymbolOfNode(entityName.parent.parent);
66882             }
66883         }
66884         function isImportTypeQualifierPart(node) {
66885             var parent = node.parent;
66886             while (ts.isQualifiedName(parent)) {
66887                 node = parent;
66888                 parent = parent.parent;
66889             }
66890             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
66891                 return parent;
66892             }
66893             return undefined;
66894         }
66895         function getSymbolOfNameOrPropertyAccessExpression(name) {
66896             if (ts.isDeclarationName(name)) {
66897                 return getSymbolOfNode(name.parent);
66898             }
66899             if (ts.isInJSFile(name) &&
66900                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
66901                 name.parent === name.parent.parent.left) {
66902                 // Check if this is a special property assignment
66903                 if (!ts.isPrivateIdentifier(name)) {
66904                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
66905                     if (specialPropertyAssignmentSymbol) {
66906                         return specialPropertyAssignmentSymbol;
66907                     }
66908                 }
66909             }
66910             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
66911                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
66912                 var success = resolveEntityName(name, 
66913                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
66914                 if (success && success !== unknownSymbol) {
66915                     return success;
66916                 }
66917             }
66918             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
66919                 // Since we already checked for ExportAssignment, this really could only be an Import
66920                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
66921                 ts.Debug.assert(importEqualsDeclaration !== undefined);
66922                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
66923             }
66924             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
66925                 var possibleImportNode = isImportTypeQualifierPart(name);
66926                 if (possibleImportNode) {
66927                     getTypeFromTypeNode(possibleImportNode);
66928                     var sym = getNodeLinks(name).resolvedSymbol;
66929                     return sym === unknownSymbol ? undefined : sym;
66930                 }
66931             }
66932             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
66933                 name = name.parent;
66934             }
66935             if (isHeritageClauseElementIdentifier(name)) {
66936                 var meaning = 0 /* None */;
66937                 // In an interface or class, we're definitely interested in a type.
66938                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
66939                     meaning = 788968 /* Type */;
66940                     // In a class 'extends' clause we are also looking for a value.
66941                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
66942                         meaning |= 111551 /* Value */;
66943                     }
66944                 }
66945                 else {
66946                     meaning = 1920 /* Namespace */;
66947                 }
66948                 meaning |= 2097152 /* Alias */;
66949                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
66950                 if (entityNameSymbol) {
66951                     return entityNameSymbol;
66952                 }
66953             }
66954             if (name.parent.kind === 317 /* JSDocParameterTag */) {
66955                 return ts.getParameterSymbolFromJSDoc(name.parent);
66956             }
66957             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
66958                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
66959                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
66960                 return typeParameter && typeParameter.symbol;
66961             }
66962             if (ts.isExpressionNode(name)) {
66963                 if (ts.nodeIsMissing(name)) {
66964                     // Missing entity name.
66965                     return undefined;
66966                 }
66967                 if (name.kind === 75 /* Identifier */) {
66968                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
66969                         var symbol = getIntrinsicTagSymbol(name.parent);
66970                         return symbol === unknownSymbol ? undefined : symbol;
66971                     }
66972                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
66973                 }
66974                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
66975                     var links = getNodeLinks(name);
66976                     if (links.resolvedSymbol) {
66977                         return links.resolvedSymbol;
66978                     }
66979                     if (name.kind === 194 /* PropertyAccessExpression */) {
66980                         checkPropertyAccessExpression(name);
66981                     }
66982                     else {
66983                         checkQualifiedName(name);
66984                     }
66985                     return links.resolvedSymbol;
66986                 }
66987             }
66988             else if (isTypeReferenceIdentifier(name)) {
66989                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
66990                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
66991             }
66992             if (name.parent.kind === 168 /* TypePredicate */) {
66993                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
66994             }
66995             // Do we want to return undefined here?
66996             return undefined;
66997         }
66998         function getSymbolAtLocation(node, ignoreErrors) {
66999             if (node.kind === 290 /* SourceFile */) {
67000                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67001             }
67002             var parent = node.parent;
67003             var grandParent = parent.parent;
67004             if (node.flags & 16777216 /* InWithStatement */) {
67005                 // We cannot answer semantic questions within a with block, do not proceed any further
67006                 return undefined;
67007             }
67008             if (isDeclarationNameOrImportPropertyName(node)) {
67009                 // This is a declaration, call getSymbolOfNode
67010                 var parentSymbol = getSymbolOfNode(parent);
67011                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67012                     ? getImmediateAliasedSymbol(parentSymbol)
67013                     : parentSymbol;
67014             }
67015             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67016                 return getSymbolOfNode(parent.parent);
67017             }
67018             if (node.kind === 75 /* Identifier */) {
67019                 if (isInRightSideOfImportOrExportAssignment(node)) {
67020                     return getSymbolOfNameOrPropertyAccessExpression(node);
67021                 }
67022                 else if (parent.kind === 191 /* BindingElement */ &&
67023                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67024                     node === parent.propertyName) {
67025                     var typeOfPattern = getTypeOfNode(grandParent);
67026                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67027                     if (propertyDeclaration) {
67028                         return propertyDeclaration;
67029                     }
67030                 }
67031             }
67032             switch (node.kind) {
67033                 case 75 /* Identifier */:
67034                 case 76 /* PrivateIdentifier */:
67035                 case 194 /* PropertyAccessExpression */:
67036                 case 153 /* QualifiedName */:
67037                     return getSymbolOfNameOrPropertyAccessExpression(node);
67038                 case 104 /* ThisKeyword */:
67039                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67040                     if (ts.isFunctionLike(container)) {
67041                         var sig = getSignatureFromDeclaration(container);
67042                         if (sig.thisParameter) {
67043                             return sig.thisParameter;
67044                         }
67045                     }
67046                     if (ts.isInExpressionContext(node)) {
67047                         return checkExpression(node).symbol;
67048                     }
67049                 // falls through
67050                 case 183 /* ThisType */:
67051                     return getTypeFromThisTypeNode(node).symbol;
67052                 case 102 /* SuperKeyword */:
67053                     return checkExpression(node).symbol;
67054                 case 129 /* ConstructorKeyword */:
67055                     // constructor keyword for an overload, should take us to the definition if it exist
67056                     var constructorDeclaration = node.parent;
67057                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67058                         return constructorDeclaration.parent.symbol;
67059                     }
67060                     return undefined;
67061                 case 10 /* StringLiteral */:
67062                 case 14 /* NoSubstitutionTemplateLiteral */:
67063                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67064                     // 2). External module name in an import declaration
67065                     // 3). Dynamic import call or require in javascript
67066                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67067                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67068                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67069                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67070                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67071                         return resolveExternalModuleName(node, node, ignoreErrors);
67072                     }
67073                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67074                         return getSymbolOfNode(parent);
67075                     }
67076                 // falls through
67077                 case 8 /* NumericLiteral */:
67078                     // index access
67079                     var objectType = ts.isElementAccessExpression(parent)
67080                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67081                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67082                             ? getTypeFromTypeNode(grandParent.objectType)
67083                             : undefined;
67084                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67085                 case 84 /* DefaultKeyword */:
67086                 case 94 /* FunctionKeyword */:
67087                 case 38 /* EqualsGreaterThanToken */:
67088                 case 80 /* ClassKeyword */:
67089                     return getSymbolOfNode(node.parent);
67090                 case 188 /* ImportType */:
67091                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67092                 case 89 /* ExportKeyword */:
67093                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67094                 default:
67095                     return undefined;
67096             }
67097         }
67098         function getShorthandAssignmentValueSymbol(location) {
67099             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67100                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67101             }
67102             return undefined;
67103         }
67104         /** Returns the target of an export specifier without following aliases */
67105         function getExportSpecifierLocalTargetSymbol(node) {
67106             return node.parent.parent.moduleSpecifier ?
67107                 getExternalModuleMember(node.parent.parent, node) :
67108                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67109         }
67110         function getTypeOfNode(node) {
67111             if (node.flags & 16777216 /* InWithStatement */) {
67112                 // We cannot answer semantic questions within a with block, do not proceed any further
67113                 return errorType;
67114             }
67115             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67116             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67117             if (ts.isPartOfTypeNode(node)) {
67118                 var typeFromTypeNode = getTypeFromTypeNode(node);
67119                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67120             }
67121             if (ts.isExpressionNode(node)) {
67122                 return getRegularTypeOfExpression(node);
67123             }
67124             if (classType && !classDecl.isImplements) {
67125                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67126                 // extends clause of a class. We handle that case here.
67127                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67128                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67129             }
67130             if (isTypeDeclaration(node)) {
67131                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67132                 var symbol = getSymbolOfNode(node);
67133                 return getDeclaredTypeOfSymbol(symbol);
67134             }
67135             if (isTypeDeclarationName(node)) {
67136                 var symbol = getSymbolAtLocation(node);
67137                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67138             }
67139             if (ts.isDeclaration(node)) {
67140                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67141                 var symbol = getSymbolOfNode(node);
67142                 return getTypeOfSymbol(symbol);
67143             }
67144             if (isDeclarationNameOrImportPropertyName(node)) {
67145                 var symbol = getSymbolAtLocation(node);
67146                 if (symbol) {
67147                     return getTypeOfSymbol(symbol);
67148                 }
67149                 return errorType;
67150             }
67151             if (ts.isBindingPattern(node)) {
67152                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67153             }
67154             if (isInRightSideOfImportOrExportAssignment(node)) {
67155                 var symbol = getSymbolAtLocation(node);
67156                 if (symbol) {
67157                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67158                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67159                 }
67160             }
67161             return errorType;
67162         }
67163         // Gets the type of object literal or array literal of destructuring assignment.
67164         // { a } from
67165         //     for ( { a } of elems) {
67166         //     }
67167         // [ a ] from
67168         //     [a] = [ some array ...]
67169         function getTypeOfAssignmentPattern(expr) {
67170             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67171             // If this is from "for of"
67172             //     for ( { a } of elems) {
67173             //     }
67174             if (expr.parent.kind === 232 /* ForOfStatement */) {
67175                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67176                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67177             }
67178             // If this is from "for" initializer
67179             //     for ({a } = elems[0];.....) { }
67180             if (expr.parent.kind === 209 /* BinaryExpression */) {
67181                 var iteratedType = getTypeOfExpression(expr.parent.right);
67182                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67183             }
67184             // If this is from nested object binding pattern
67185             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67186             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67187                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67188                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67189                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67190                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67191             }
67192             // Array literal assignment - array destructuring pattern
67193             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67194             //    [{ property1: p1, property2 }] = elems;
67195             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67196             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67197             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67198         }
67199         // Gets the property symbol corresponding to the property in destructuring assignment
67200         // 'property1' from
67201         //     for ( { property1: a } of elems) {
67202         //     }
67203         // 'property1' at location 'a' from:
67204         //     [a] = [ property1, property2 ]
67205         function getPropertySymbolOfDestructuringAssignment(location) {
67206             // Get the type of the object or array literal and then look for property of given name in the type
67207             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67208             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67209         }
67210         function getRegularTypeOfExpression(expr) {
67211             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67212                 expr = expr.parent;
67213             }
67214             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67215         }
67216         /**
67217          * Gets either the static or instance type of a class element, based on
67218          * whether the element is declared as "static".
67219          */
67220         function getParentTypeOfClassElement(node) {
67221             var classSymbol = getSymbolOfNode(node.parent);
67222             return ts.hasModifier(node, 32 /* Static */)
67223                 ? getTypeOfSymbol(classSymbol)
67224                 : getDeclaredTypeOfSymbol(classSymbol);
67225         }
67226         function getClassElementPropertyKeyType(element) {
67227             var name = element.name;
67228             switch (name.kind) {
67229                 case 75 /* Identifier */:
67230                     return getLiteralType(ts.idText(name));
67231                 case 8 /* NumericLiteral */:
67232                 case 10 /* StringLiteral */:
67233                     return getLiteralType(name.text);
67234                 case 154 /* ComputedPropertyName */:
67235                     var nameType = checkComputedPropertyName(name);
67236                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67237                 default:
67238                     return ts.Debug.fail("Unsupported property name.");
67239             }
67240         }
67241         // Return the list of properties of the given type, augmented with properties from Function
67242         // if the type has call or construct signatures
67243         function getAugmentedPropertiesOfType(type) {
67244             type = getApparentType(type);
67245             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67246             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67247                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67248                     undefined;
67249             if (functionType) {
67250                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67251                     if (!propsByName.has(p.escapedName)) {
67252                         propsByName.set(p.escapedName, p);
67253                     }
67254                 });
67255             }
67256             return getNamedMembers(propsByName);
67257         }
67258         function typeHasCallOrConstructSignatures(type) {
67259             return ts.typeHasCallOrConstructSignatures(type, checker);
67260         }
67261         function getRootSymbols(symbol) {
67262             var roots = getImmediateRootSymbols(symbol);
67263             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67264         }
67265         function getImmediateRootSymbols(symbol) {
67266             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67267                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67268             }
67269             else if (symbol.flags & 33554432 /* Transient */) {
67270                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67271                 return leftSpread ? [leftSpread, rightSpread]
67272                     : syntheticOrigin ? [syntheticOrigin]
67273                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67274             }
67275             return undefined;
67276         }
67277         function tryGetAliasTarget(symbol) {
67278             var target;
67279             var next = symbol;
67280             while (next = getSymbolLinks(next).target) {
67281                 target = next;
67282             }
67283             return target;
67284         }
67285         // Emitter support
67286         function isArgumentsLocalBinding(nodeIn) {
67287             if (!ts.isGeneratedIdentifier(nodeIn)) {
67288                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67289                 if (node) {
67290                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67291                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67292                 }
67293             }
67294             return false;
67295         }
67296         function moduleExportsSomeValue(moduleReferenceExpression) {
67297             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67298             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67299                 // If the module is not found or is shorthand, assume that it may export a value.
67300                 return true;
67301             }
67302             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67303             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67304             // otherwise it will return moduleSymbol itself
67305             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67306             var symbolLinks = getSymbolLinks(moduleSymbol);
67307             if (symbolLinks.exportsSomeValue === undefined) {
67308                 // for export assignments - check if resolved symbol for RHS is itself a value
67309                 // otherwise - check if at least one export is value
67310                 symbolLinks.exportsSomeValue = hasExportAssignment
67311                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67312                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67313             }
67314             return symbolLinks.exportsSomeValue;
67315             function isValue(s) {
67316                 s = resolveSymbol(s);
67317                 return s && !!(s.flags & 111551 /* Value */);
67318             }
67319         }
67320         function isNameOfModuleOrEnumDeclaration(node) {
67321             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67322         }
67323         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67324         // node of the exported entity's container. Otherwise, return undefined.
67325         function getReferencedExportContainer(nodeIn, prefixLocals) {
67326             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67327             if (node) {
67328                 // When resolving the export container for the name of a module or enum
67329                 // declaration, we need to start resolution at the declaration's container.
67330                 // Otherwise, we could incorrectly resolve the export container as the
67331                 // declaration if it contains an exported member with the same name.
67332                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67333                 if (symbol) {
67334                     if (symbol.flags & 1048576 /* ExportValue */) {
67335                         // If we reference an exported entity within the same module declaration, then whether
67336                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67337                         // kinds that we do NOT prefix.
67338                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67339                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67340                             return undefined;
67341                         }
67342                         symbol = exportSymbol;
67343                     }
67344                     var parentSymbol_1 = getParentOfSymbol(symbol);
67345                     if (parentSymbol_1) {
67346                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67347                             var symbolFile = parentSymbol_1.valueDeclaration;
67348                             var referenceFile = ts.getSourceFileOfNode(node);
67349                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67350                             var symbolIsUmdExport = symbolFile !== referenceFile;
67351                             return symbolIsUmdExport ? undefined : symbolFile;
67352                         }
67353                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67354                     }
67355                 }
67356             }
67357         }
67358         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67359         // that import. Otherwise, return undefined.
67360         function getReferencedImportDeclaration(nodeIn) {
67361             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67362             if (node) {
67363                 var symbol = getReferencedValueSymbol(node);
67364                 // We should only get the declaration of an alias if there isn't a local value
67365                 // declaration for the symbol
67366                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67367                     return getDeclarationOfAliasSymbol(symbol);
67368                 }
67369             }
67370             return undefined;
67371         }
67372         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67373             return ts.isBindingElement(symbol.valueDeclaration)
67374                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67375         }
67376         function isSymbolOfDeclarationWithCollidingName(symbol) {
67377             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67378                 var links = getSymbolLinks(symbol);
67379                 if (links.isDeclarationWithCollidingName === undefined) {
67380                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67381                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67382                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67383                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67384                             // redeclaration - always should be renamed
67385                             links.isDeclarationWithCollidingName = true;
67386                         }
67387                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67388                             // binding is captured in the function
67389                             // should be renamed if:
67390                             // - binding is not top level - top level bindings never collide with anything
67391                             // AND
67392                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67393                             //     let a, b
67394                             //     { let x = 1; a = () => x; }
67395                             //     { let x = 100; b = () => x; }
67396                             //     console.log(a()); // should print '1'
67397                             //     console.log(b()); // should print '100'
67398                             //     OR
67399                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67400                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67401                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67402                             //       they will not collide with anything
67403                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67404                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67405                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67406                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67407                         }
67408                         else {
67409                             links.isDeclarationWithCollidingName = false;
67410                         }
67411                     }
67412                 }
67413                 return links.isDeclarationWithCollidingName;
67414             }
67415             return false;
67416         }
67417         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67418         // a name that either hides an existing name or might hide it when compiled downlevel,
67419         // return the declaration of that entity. Otherwise, return undefined.
67420         function getReferencedDeclarationWithCollidingName(nodeIn) {
67421             if (!ts.isGeneratedIdentifier(nodeIn)) {
67422                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67423                 if (node) {
67424                     var symbol = getReferencedValueSymbol(node);
67425                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67426                         return symbol.valueDeclaration;
67427                     }
67428                 }
67429             }
67430             return undefined;
67431         }
67432         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67433         // existing name or might hide a name when compiled downlevel
67434         function isDeclarationWithCollidingName(nodeIn) {
67435             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67436             if (node) {
67437                 var symbol = getSymbolOfNode(node);
67438                 if (symbol) {
67439                     return isSymbolOfDeclarationWithCollidingName(symbol);
67440                 }
67441             }
67442             return false;
67443         }
67444         function isValueAliasDeclaration(node) {
67445             switch (node.kind) {
67446                 case 253 /* ImportEqualsDeclaration */:
67447                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67448                 case 255 /* ImportClause */:
67449                 case 256 /* NamespaceImport */:
67450                 case 258 /* ImportSpecifier */:
67451                 case 263 /* ExportSpecifier */:
67452                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67453                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67454                 case 260 /* ExportDeclaration */:
67455                     var exportClause = node.exportClause;
67456                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67457                         ts.some(exportClause.elements, isValueAliasDeclaration));
67458                 case 259 /* ExportAssignment */:
67459                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67460                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67461                         true;
67462             }
67463             return false;
67464         }
67465         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67466             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67467             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67468                 // parent is not source file or it is not reference to internal module
67469                 return false;
67470             }
67471             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67472             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67473         }
67474         function isAliasResolvedToValue(symbol) {
67475             var target = resolveAlias(symbol);
67476             if (target === unknownSymbol) {
67477                 return true;
67478             }
67479             // const enums and modules that contain only const enums are not considered values from the emit perspective
67480             // unless 'preserveConstEnums' option is set to true
67481             return !!(target.flags & 111551 /* Value */) &&
67482                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67483         }
67484         function isConstEnumOrConstEnumOnlyModule(s) {
67485             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67486         }
67487         function isReferencedAliasDeclaration(node, checkChildren) {
67488             if (isAliasSymbolDeclaration(node)) {
67489                 var symbol = getSymbolOfNode(node);
67490                 if (symbol && getSymbolLinks(symbol).referenced) {
67491                     return true;
67492                 }
67493                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67494                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67495                     target.flags & 111551 /* Value */ &&
67496                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67497                     // An `export import ... =` of a value symbol is always considered referenced
67498                     return true;
67499                 }
67500             }
67501             if (checkChildren) {
67502                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67503             }
67504             return false;
67505         }
67506         function isImplementationOfOverload(node) {
67507             if (ts.nodeIsPresent(node.body)) {
67508                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67509                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67510                 var symbol = getSymbolOfNode(node);
67511                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67512                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67513                 // e.g.: function foo(a: string): string;
67514                 //       function foo(a: number): number;
67515                 //       function foo(a: any) { // This is implementation of the overloads
67516                 //           return a;
67517                 //       }
67518                 return signaturesOfSymbol.length > 1 ||
67519                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67520                     // e.g.: function foo(a: string): string;
67521                     //       function foo(a: any) { // This is implementation of the overloads
67522                     //           return a;
67523                     //       }
67524                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67525             }
67526             return false;
67527         }
67528         function isRequiredInitializedParameter(parameter) {
67529             return !!strictNullChecks &&
67530                 !isOptionalParameter(parameter) &&
67531                 !ts.isJSDocParameterTag(parameter) &&
67532                 !!parameter.initializer &&
67533                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67534         }
67535         function isOptionalUninitializedParameterProperty(parameter) {
67536             return strictNullChecks &&
67537                 isOptionalParameter(parameter) &&
67538                 !parameter.initializer &&
67539                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67540         }
67541         function isExpandoFunctionDeclaration(node) {
67542             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67543             if (!declaration) {
67544                 return false;
67545             }
67546             var symbol = getSymbolOfNode(declaration);
67547             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67548                 return false;
67549             }
67550             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67551         }
67552         function getPropertiesOfContainerFunction(node) {
67553             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67554             if (!declaration) {
67555                 return ts.emptyArray;
67556             }
67557             var symbol = getSymbolOfNode(declaration);
67558             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67559         }
67560         function getNodeCheckFlags(node) {
67561             return getNodeLinks(node).flags || 0;
67562         }
67563         function getEnumMemberValue(node) {
67564             computeEnumMemberValues(node.parent);
67565             return getNodeLinks(node).enumMemberValue;
67566         }
67567         function canHaveConstantValue(node) {
67568             switch (node.kind) {
67569                 case 284 /* EnumMember */:
67570                 case 194 /* PropertyAccessExpression */:
67571                 case 195 /* ElementAccessExpression */:
67572                     return true;
67573             }
67574             return false;
67575         }
67576         function getConstantValue(node) {
67577             if (node.kind === 284 /* EnumMember */) {
67578                 return getEnumMemberValue(node);
67579             }
67580             var symbol = getNodeLinks(node).resolvedSymbol;
67581             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67582                 // inline property\index accesses only for const enums
67583                 var member = symbol.valueDeclaration;
67584                 if (ts.isEnumConst(member.parent)) {
67585                     return getEnumMemberValue(member);
67586                 }
67587             }
67588             return undefined;
67589         }
67590         function isFunctionType(type) {
67591             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67592         }
67593         function getTypeReferenceSerializationKind(typeNameIn, location) {
67594             // ensure both `typeName` and `location` are parse tree nodes.
67595             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67596             if (!typeName)
67597                 return ts.TypeReferenceSerializationKind.Unknown;
67598             if (location) {
67599                 location = ts.getParseTreeNode(location);
67600                 if (!location)
67601                     return ts.TypeReferenceSerializationKind.Unknown;
67602             }
67603             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67604             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67605             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67606             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67607             if (valueSymbol && valueSymbol === typeSymbol) {
67608                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67609                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67610                     return ts.TypeReferenceSerializationKind.Promise;
67611                 }
67612                 var constructorType = getTypeOfSymbol(valueSymbol);
67613                 if (constructorType && isConstructorType(constructorType)) {
67614                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67615                 }
67616             }
67617             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67618             if (!typeSymbol) {
67619                 return ts.TypeReferenceSerializationKind.Unknown;
67620             }
67621             var type = getDeclaredTypeOfSymbol(typeSymbol);
67622             if (type === errorType) {
67623                 return ts.TypeReferenceSerializationKind.Unknown;
67624             }
67625             else if (type.flags & 3 /* AnyOrUnknown */) {
67626                 return ts.TypeReferenceSerializationKind.ObjectType;
67627             }
67628             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67629                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67630             }
67631             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67632                 return ts.TypeReferenceSerializationKind.BooleanType;
67633             }
67634             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67635                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67636             }
67637             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67638                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67639             }
67640             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67641                 return ts.TypeReferenceSerializationKind.StringLikeType;
67642             }
67643             else if (isTupleType(type)) {
67644                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67645             }
67646             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67647                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67648             }
67649             else if (isFunctionType(type)) {
67650                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67651             }
67652             else if (isArrayType(type)) {
67653                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67654             }
67655             else {
67656                 return ts.TypeReferenceSerializationKind.ObjectType;
67657             }
67658         }
67659         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67660             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67661             if (!declaration) {
67662                 return ts.createToken(125 /* AnyKeyword */);
67663             }
67664             // Get type of the symbol if this is the valid symbol otherwise get type at location
67665             var symbol = getSymbolOfNode(declaration);
67666             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67667                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67668                 : errorType;
67669             if (type.flags & 8192 /* UniqueESSymbol */ &&
67670                 type.symbol === symbol) {
67671                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67672             }
67673             if (addUndefined) {
67674                 type = getOptionalType(type);
67675             }
67676             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67677         }
67678         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67679             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67680             if (!signatureDeclaration) {
67681                 return ts.createToken(125 /* AnyKeyword */);
67682             }
67683             var signature = getSignatureFromDeclaration(signatureDeclaration);
67684             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67685         }
67686         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67687             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67688             if (!expr) {
67689                 return ts.createToken(125 /* AnyKeyword */);
67690             }
67691             var type = getWidenedType(getRegularTypeOfExpression(expr));
67692             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67693         }
67694         function hasGlobalName(name) {
67695             return globals.has(ts.escapeLeadingUnderscores(name));
67696         }
67697         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67698             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67699             if (resolvedSymbol) {
67700                 return resolvedSymbol;
67701             }
67702             var location = reference;
67703             if (startInDeclarationContainer) {
67704                 // When resolving the name of a declaration as a value, we need to start resolution
67705                 // at a point outside of the declaration.
67706                 var parent = reference.parent;
67707                 if (ts.isDeclaration(parent) && reference === parent.name) {
67708                     location = getDeclarationContainer(parent);
67709                 }
67710             }
67711             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67712         }
67713         function getReferencedValueDeclaration(referenceIn) {
67714             if (!ts.isGeneratedIdentifier(referenceIn)) {
67715                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67716                 if (reference) {
67717                     var symbol = getReferencedValueSymbol(reference);
67718                     if (symbol) {
67719                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67720                     }
67721                 }
67722             }
67723             return undefined;
67724         }
67725         function isLiteralConstDeclaration(node) {
67726             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67727                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67728             }
67729             return false;
67730         }
67731         function literalTypeToNode(type, enclosing, tracker) {
67732             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67733                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67734             return enumResult || ts.createLiteral(type.value);
67735         }
67736         function createLiteralConstValue(node, tracker) {
67737             var type = getTypeOfSymbol(getSymbolOfNode(node));
67738             return literalTypeToNode(type, node, tracker);
67739         }
67740         function getJsxFactoryEntity(location) {
67741             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67742         }
67743         function createResolver() {
67744             // this variable and functions that use it are deliberately moved here from the outer scope
67745             // to avoid scope pollution
67746             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67747             var fileToDirective;
67748             if (resolvedTypeReferenceDirectives) {
67749                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67750                 fileToDirective = ts.createMap();
67751                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67752                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67753                         return;
67754                     }
67755                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67756                     if (file) {
67757                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67758                         // part of an existing type reference.
67759                         addReferencedFilesToTypeDirective(file, key);
67760                     }
67761                 });
67762             }
67763             return {
67764                 getReferencedExportContainer: getReferencedExportContainer,
67765                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67766                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67767                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67768                 isValueAliasDeclaration: function (node) {
67769                     node = ts.getParseTreeNode(node);
67770                     // Synthesized nodes are always treated like values.
67771                     return node ? isValueAliasDeclaration(node) : true;
67772                 },
67773                 hasGlobalName: hasGlobalName,
67774                 isReferencedAliasDeclaration: function (node, checkChildren) {
67775                     node = ts.getParseTreeNode(node);
67776                     // Synthesized nodes are always treated as referenced.
67777                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67778                 },
67779                 getNodeCheckFlags: function (node) {
67780                     node = ts.getParseTreeNode(node);
67781                     return node ? getNodeCheckFlags(node) : 0;
67782                 },
67783                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67784                 isDeclarationVisible: isDeclarationVisible,
67785                 isImplementationOfOverload: isImplementationOfOverload,
67786                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67787                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67788                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67789                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67790                 createTypeOfDeclaration: createTypeOfDeclaration,
67791                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67792                 createTypeOfExpression: createTypeOfExpression,
67793                 createLiteralConstValue: createLiteralConstValue,
67794                 isSymbolAccessible: isSymbolAccessible,
67795                 isEntityNameVisible: isEntityNameVisible,
67796                 getConstantValue: function (nodeIn) {
67797                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67798                     return node ? getConstantValue(node) : undefined;
67799                 },
67800                 collectLinkedAliases: collectLinkedAliases,
67801                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67802                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67803                 isOptionalParameter: isOptionalParameter,
67804                 moduleExportsSomeValue: moduleExportsSomeValue,
67805                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67806                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67807                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67808                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67809                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67810                 isLateBound: function (nodeIn) {
67811                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67812                     var symbol = node && getSymbolOfNode(node);
67813                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67814                 },
67815                 getJsxFactoryEntity: getJsxFactoryEntity,
67816                 getAllAccessorDeclarations: function (accessor) {
67817                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
67818                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
67819                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
67820                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
67821                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
67822                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
67823                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
67824                     return {
67825                         firstAccessor: firstAccessor,
67826                         secondAccessor: secondAccessor,
67827                         setAccessor: setAccessor,
67828                         getAccessor: getAccessor
67829                     };
67830                 },
67831                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
67832                 isBindingCapturedByNode: function (node, decl) {
67833                     var parseNode = ts.getParseTreeNode(node);
67834                     var parseDecl = ts.getParseTreeNode(decl);
67835                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
67836                 },
67837                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
67838                     var n = ts.getParseTreeNode(node);
67839                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
67840                     var sym = getSymbolOfNode(node);
67841                     if (!sym) {
67842                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
67843                     }
67844                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
67845                 },
67846                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
67847             };
67848             function isImportRequiredByAugmentation(node) {
67849                 var file = ts.getSourceFileOfNode(node);
67850                 if (!file.symbol)
67851                     return false;
67852                 var importTarget = getExternalModuleFileFromDeclaration(node);
67853                 if (!importTarget)
67854                     return false;
67855                 if (importTarget === file)
67856                     return false;
67857                 var exports = getExportsOfModule(file.symbol);
67858                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
67859                     var s = _a[_i];
67860                     if (s.mergeId) {
67861                         var merged = getMergedSymbol(s);
67862                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
67863                             var d = _c[_b];
67864                             var declFile = ts.getSourceFileOfNode(d);
67865                             if (declFile === importTarget) {
67866                                 return true;
67867                             }
67868                         }
67869                     }
67870                 }
67871                 return false;
67872             }
67873             function isInHeritageClause(node) {
67874                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
67875             }
67876             // defined here to avoid outer scope pollution
67877             function getTypeReferenceDirectivesForEntityName(node) {
67878                 // program does not have any files with type reference directives - bail out
67879                 if (!fileToDirective) {
67880                     return undefined;
67881                 }
67882                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
67883                 // qualified names can only be used as types\namespaces
67884                 // identifiers are treated as values only if they appear in type queries
67885                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
67886                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
67887                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
67888                 }
67889                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
67890                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
67891             }
67892             // defined here to avoid outer scope pollution
67893             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
67894                 // program does not have any files with type reference directives - bail out
67895                 if (!fileToDirective) {
67896                     return undefined;
67897                 }
67898                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
67899                     return undefined;
67900                 }
67901                 // check what declarations in the symbol can contribute to the target meaning
67902                 var typeReferenceDirectives;
67903                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67904                     var decl = _a[_i];
67905                     // check meaning of the local symbol to see if declaration needs to be analyzed further
67906                     if (decl.symbol && decl.symbol.flags & meaning) {
67907                         var file = ts.getSourceFileOfNode(decl);
67908                         var typeReferenceDirective = fileToDirective.get(file.path);
67909                         if (typeReferenceDirective) {
67910                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
67911                         }
67912                         else {
67913                             // found at least one entry that does not originate from type reference directive
67914                             return undefined;
67915                         }
67916                     }
67917                 }
67918                 return typeReferenceDirectives;
67919             }
67920             function isSymbolFromTypeDeclarationFile(symbol) {
67921                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
67922                 if (!symbol.declarations) {
67923                     return false;
67924                 }
67925                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
67926                 // external modules cannot define or contribute to type declaration files
67927                 var current = symbol;
67928                 while (true) {
67929                     var parent = getParentOfSymbol(current);
67930                     if (parent) {
67931                         current = parent;
67932                     }
67933                     else {
67934                         break;
67935                     }
67936                 }
67937                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
67938                     return false;
67939                 }
67940                 // check that at least one declaration of top level symbol originates from type declaration file
67941                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67942                     var decl = _a[_i];
67943                     var file = ts.getSourceFileOfNode(decl);
67944                     if (fileToDirective.has(file.path)) {
67945                         return true;
67946                     }
67947                 }
67948                 return false;
67949             }
67950             function addReferencedFilesToTypeDirective(file, key) {
67951                 if (fileToDirective.has(file.path))
67952                     return;
67953                 fileToDirective.set(file.path, key);
67954                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
67955                     var fileName = _a[_i].fileName;
67956                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
67957                     var referencedFile = host.getSourceFile(resolvedFile);
67958                     if (referencedFile) {
67959                         addReferencedFilesToTypeDirective(referencedFile, key);
67960                     }
67961                 }
67962             }
67963         }
67964         function getExternalModuleFileFromDeclaration(declaration) {
67965             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
67966             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
67967             if (!moduleSymbol) {
67968                 return undefined;
67969             }
67970             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
67971         }
67972         function initializeTypeChecker() {
67973             // Bind all source files and propagate errors
67974             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
67975                 var file = _a[_i];
67976                 ts.bindSourceFile(file, compilerOptions);
67977             }
67978             amalgamatedDuplicates = ts.createMap();
67979             // Initialize global symbol table
67980             var augmentations;
67981             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
67982                 var file = _c[_b];
67983                 if (file.redirectInfo) {
67984                     continue;
67985                 }
67986                 if (!ts.isExternalOrCommonJsModule(file)) {
67987                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
67988                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
67989                     var fileGlobalThisSymbol = file.locals.get("globalThis");
67990                     if (fileGlobalThisSymbol) {
67991                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
67992                             var declaration = _e[_d];
67993                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
67994                         }
67995                     }
67996                     mergeSymbolTable(globals, file.locals);
67997                 }
67998                 if (file.jsGlobalAugmentations) {
67999                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68000                 }
68001                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68002                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68003                 }
68004                 if (file.moduleAugmentations.length) {
68005                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68006                 }
68007                 if (file.symbol && file.symbol.globalExports) {
68008                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68009                     var source = file.symbol.globalExports;
68010                     source.forEach(function (sourceSymbol, id) {
68011                         if (!globals.has(id)) {
68012                             globals.set(id, sourceSymbol);
68013                         }
68014                     });
68015                 }
68016             }
68017             // We do global augmentations separately from module augmentations (and before creating global types) because they
68018             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68019             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68020             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68021             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68022             //       did module augmentations prior to finalizing the global types.
68023             if (augmentations) {
68024                 // merge _global_ module augmentations.
68025                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68026                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68027                     var list = augmentations_1[_f];
68028                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68029                         var augmentation = list_1[_g];
68030                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68031                             continue;
68032                         mergeModuleAugmentation(augmentation);
68033                     }
68034                 }
68035             }
68036             // Setup global builtins
68037             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68038             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68039             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68040             getSymbolLinks(unknownSymbol).type = errorType;
68041             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68042             // Initialize special types
68043             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68044             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68045             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68046             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68047             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68048             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68049             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68050             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68051             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68052             anyArrayType = createArrayType(anyType);
68053             autoArrayType = createArrayType(autoType);
68054             if (autoArrayType === emptyObjectType) {
68055                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68056                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68057             }
68058             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68059             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68060             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68061             if (augmentations) {
68062                 // merge _nonglobal_ module augmentations.
68063                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68064                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68065                     var list = augmentations_2[_h];
68066                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68067                         var augmentation = list_2[_j];
68068                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68069                             continue;
68070                         mergeModuleAugmentation(augmentation);
68071                     }
68072                 }
68073             }
68074             amalgamatedDuplicates.forEach(function (_a) {
68075                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68076                 // If not many things conflict, issue individual errors
68077                 if (conflictingSymbols.size < 8) {
68078                     conflictingSymbols.forEach(function (_a, symbolName) {
68079                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68080                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68081                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68082                             var node = firstFileLocations_1[_i];
68083                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68084                         }
68085                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68086                             var node = secondFileLocations_1[_b];
68087                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68088                         }
68089                     });
68090                 }
68091                 else {
68092                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68093                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68094                     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)));
68095                     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)));
68096                 }
68097             });
68098             amalgamatedDuplicates = undefined;
68099         }
68100         function checkExternalEmitHelpers(location, helpers) {
68101             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68102                 var sourceFile = ts.getSourceFileOfNode(location);
68103                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68104                     var helpersModule = resolveHelpersModule(sourceFile, location);
68105                     if (helpersModule !== unknownSymbol) {
68106                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68107                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68108                             if (uncheckedHelpers & helper) {
68109                                 var name = getHelperName(helper);
68110                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68111                                 if (!symbol) {
68112                                     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);
68113                                 }
68114                             }
68115                         }
68116                     }
68117                     requestedExternalEmitHelpers |= helpers;
68118                 }
68119             }
68120         }
68121         function getHelperName(helper) {
68122             switch (helper) {
68123                 case 1 /* Extends */: return "__extends";
68124                 case 2 /* Assign */: return "__assign";
68125                 case 4 /* Rest */: return "__rest";
68126                 case 8 /* Decorate */: return "__decorate";
68127                 case 16 /* Metadata */: return "__metadata";
68128                 case 32 /* Param */: return "__param";
68129                 case 64 /* Awaiter */: return "__awaiter";
68130                 case 128 /* Generator */: return "__generator";
68131                 case 256 /* Values */: return "__values";
68132                 case 512 /* Read */: return "__read";
68133                 case 1024 /* Spread */: return "__spread";
68134                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68135                 case 4096 /* Await */: return "__await";
68136                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68137                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68138                 case 32768 /* AsyncValues */: return "__asyncValues";
68139                 case 65536 /* ExportStar */: return "__exportStar";
68140                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68141                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68142                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68143                 case 1048576 /* CreateBinding */: return "__createBinding";
68144                 default: return ts.Debug.fail("Unrecognized helper");
68145             }
68146         }
68147         function resolveHelpersModule(node, errorNode) {
68148             if (!externalHelpersModule) {
68149                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68150             }
68151             return externalHelpersModule;
68152         }
68153         // GRAMMAR CHECKING
68154         function checkGrammarDecoratorsAndModifiers(node) {
68155             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68156         }
68157         function checkGrammarDecorators(node) {
68158             if (!node.decorators) {
68159                 return false;
68160             }
68161             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68162                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68163                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68164                 }
68165                 else {
68166                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68167                 }
68168             }
68169             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68170                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68171                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68172                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68173                 }
68174             }
68175             return false;
68176         }
68177         function checkGrammarModifiers(node) {
68178             var quickResult = reportObviousModifierErrors(node);
68179             if (quickResult !== undefined) {
68180                 return quickResult;
68181             }
68182             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68183             var flags = 0 /* None */;
68184             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68185                 var modifier = _a[_i];
68186                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68187                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68188                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68189                     }
68190                     if (node.kind === 167 /* IndexSignature */) {
68191                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68192                     }
68193                 }
68194                 switch (modifier.kind) {
68195                     case 81 /* ConstKeyword */:
68196                         if (node.kind !== 248 /* EnumDeclaration */) {
68197                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68198                         }
68199                         break;
68200                     case 119 /* PublicKeyword */:
68201                     case 118 /* ProtectedKeyword */:
68202                     case 117 /* PrivateKeyword */:
68203                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68204                         if (flags & 28 /* AccessibilityModifier */) {
68205                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68206                         }
68207                         else if (flags & 32 /* Static */) {
68208                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68209                         }
68210                         else if (flags & 64 /* Readonly */) {
68211                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68212                         }
68213                         else if (flags & 256 /* Async */) {
68214                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68215                         }
68216                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68217                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68218                         }
68219                         else if (flags & 128 /* Abstract */) {
68220                             if (modifier.kind === 117 /* PrivateKeyword */) {
68221                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68222                             }
68223                             else {
68224                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68225                             }
68226                         }
68227                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68228                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68229                         }
68230                         flags |= ts.modifierToFlag(modifier.kind);
68231                         break;
68232                     case 120 /* StaticKeyword */:
68233                         if (flags & 32 /* Static */) {
68234                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68235                         }
68236                         else if (flags & 64 /* Readonly */) {
68237                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68238                         }
68239                         else if (flags & 256 /* Async */) {
68240                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68241                         }
68242                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68243                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68244                         }
68245                         else if (node.kind === 156 /* Parameter */) {
68246                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68247                         }
68248                         else if (flags & 128 /* Abstract */) {
68249                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68250                         }
68251                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68252                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68253                         }
68254                         flags |= 32 /* Static */;
68255                         lastStatic = modifier;
68256                         break;
68257                     case 138 /* ReadonlyKeyword */:
68258                         if (flags & 64 /* Readonly */) {
68259                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68260                         }
68261                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68262                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68263                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68264                         }
68265                         flags |= 64 /* Readonly */;
68266                         lastReadonly = modifier;
68267                         break;
68268                     case 89 /* ExportKeyword */:
68269                         if (flags & 1 /* Export */) {
68270                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68271                         }
68272                         else if (flags & 2 /* Ambient */) {
68273                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68274                         }
68275                         else if (flags & 128 /* Abstract */) {
68276                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68277                         }
68278                         else if (flags & 256 /* Async */) {
68279                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68280                         }
68281                         else if (ts.isClassLike(node.parent)) {
68282                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68283                         }
68284                         else if (node.kind === 156 /* Parameter */) {
68285                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68286                         }
68287                         flags |= 1 /* Export */;
68288                         break;
68289                     case 84 /* DefaultKeyword */:
68290                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68291                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68292                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68293                         }
68294                         flags |= 512 /* Default */;
68295                         break;
68296                     case 130 /* DeclareKeyword */:
68297                         if (flags & 2 /* Ambient */) {
68298                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68299                         }
68300                         else if (flags & 256 /* Async */) {
68301                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68302                         }
68303                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68304                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68305                         }
68306                         else if (node.kind === 156 /* Parameter */) {
68307                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68308                         }
68309                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68310                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68311                         }
68312                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68313                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68314                         }
68315                         flags |= 2 /* Ambient */;
68316                         lastDeclare = modifier;
68317                         break;
68318                     case 122 /* AbstractKeyword */:
68319                         if (flags & 128 /* Abstract */) {
68320                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68321                         }
68322                         if (node.kind !== 245 /* ClassDeclaration */) {
68323                             if (node.kind !== 161 /* MethodDeclaration */ &&
68324                                 node.kind !== 159 /* PropertyDeclaration */ &&
68325                                 node.kind !== 163 /* GetAccessor */ &&
68326                                 node.kind !== 164 /* SetAccessor */) {
68327                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68328                             }
68329                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68330                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68331                             }
68332                             if (flags & 32 /* Static */) {
68333                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68334                             }
68335                             if (flags & 8 /* Private */) {
68336                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68337                             }
68338                         }
68339                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68340                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68341                         }
68342                         flags |= 128 /* Abstract */;
68343                         break;
68344                     case 126 /* AsyncKeyword */:
68345                         if (flags & 256 /* Async */) {
68346                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68347                         }
68348                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68349                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68350                         }
68351                         else if (node.kind === 156 /* Parameter */) {
68352                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68353                         }
68354                         flags |= 256 /* Async */;
68355                         lastAsync = modifier;
68356                         break;
68357                 }
68358             }
68359             if (node.kind === 162 /* Constructor */) {
68360                 if (flags & 32 /* Static */) {
68361                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68362                 }
68363                 if (flags & 128 /* Abstract */) {
68364                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68365                 }
68366                 else if (flags & 256 /* Async */) {
68367                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68368                 }
68369                 else if (flags & 64 /* Readonly */) {
68370                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68371                 }
68372                 return false;
68373             }
68374             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68375                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68376             }
68377             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68378                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68379             }
68380             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68381                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68382             }
68383             if (flags & 256 /* Async */) {
68384                 return checkGrammarAsyncModifier(node, lastAsync);
68385             }
68386             return false;
68387         }
68388         /**
68389          * true | false: Early return this value from checkGrammarModifiers.
68390          * undefined: Need to do full checking on the modifiers.
68391          */
68392         function reportObviousModifierErrors(node) {
68393             return !node.modifiers
68394                 ? false
68395                 : shouldReportBadModifier(node)
68396                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68397                     : undefined;
68398         }
68399         function shouldReportBadModifier(node) {
68400             switch (node.kind) {
68401                 case 163 /* GetAccessor */:
68402                 case 164 /* SetAccessor */:
68403                 case 162 /* Constructor */:
68404                 case 159 /* PropertyDeclaration */:
68405                 case 158 /* PropertySignature */:
68406                 case 161 /* MethodDeclaration */:
68407                 case 160 /* MethodSignature */:
68408                 case 167 /* IndexSignature */:
68409                 case 249 /* ModuleDeclaration */:
68410                 case 254 /* ImportDeclaration */:
68411                 case 253 /* ImportEqualsDeclaration */:
68412                 case 260 /* ExportDeclaration */:
68413                 case 259 /* ExportAssignment */:
68414                 case 201 /* FunctionExpression */:
68415                 case 202 /* ArrowFunction */:
68416                 case 156 /* Parameter */:
68417                     return false;
68418                 default:
68419                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68420                         return false;
68421                     }
68422                     switch (node.kind) {
68423                         case 244 /* FunctionDeclaration */:
68424                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68425                         case 245 /* ClassDeclaration */:
68426                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68427                         case 246 /* InterfaceDeclaration */:
68428                         case 225 /* VariableStatement */:
68429                         case 247 /* TypeAliasDeclaration */:
68430                             return true;
68431                         case 248 /* EnumDeclaration */:
68432                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68433                         default:
68434                             ts.Debug.fail();
68435                             return false;
68436                     }
68437             }
68438         }
68439         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68440             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68441         }
68442         function checkGrammarAsyncModifier(node, asyncModifier) {
68443             switch (node.kind) {
68444                 case 161 /* MethodDeclaration */:
68445                 case 244 /* FunctionDeclaration */:
68446                 case 201 /* FunctionExpression */:
68447                 case 202 /* ArrowFunction */:
68448                     return false;
68449             }
68450             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68451         }
68452         function checkGrammarForDisallowedTrailingComma(list, diag) {
68453             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68454             if (list && list.hasTrailingComma) {
68455                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68456             }
68457             return false;
68458         }
68459         function checkGrammarTypeParameterList(typeParameters, file) {
68460             if (typeParameters && typeParameters.length === 0) {
68461                 var start = typeParameters.pos - "<".length;
68462                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68463                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68464             }
68465             return false;
68466         }
68467         function checkGrammarParameterList(parameters) {
68468             var seenOptionalParameter = false;
68469             var parameterCount = parameters.length;
68470             for (var i = 0; i < parameterCount; i++) {
68471                 var parameter = parameters[i];
68472                 if (parameter.dotDotDotToken) {
68473                     if (i !== (parameterCount - 1)) {
68474                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68475                     }
68476                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68477                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68478                     }
68479                     if (parameter.questionToken) {
68480                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68481                     }
68482                     if (parameter.initializer) {
68483                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68484                     }
68485                 }
68486                 else if (parameter.questionToken) {
68487                     seenOptionalParameter = true;
68488                     if (parameter.initializer) {
68489                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68490                     }
68491                 }
68492                 else if (seenOptionalParameter && !parameter.initializer) {
68493                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68494                 }
68495             }
68496         }
68497         function getNonSimpleParameters(parameters) {
68498             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68499         }
68500         function checkGrammarForUseStrictSimpleParameterList(node) {
68501             if (languageVersion >= 3 /* ES2016 */) {
68502                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68503                 if (useStrictDirective_1) {
68504                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68505                     if (ts.length(nonSimpleParameters)) {
68506                         ts.forEach(nonSimpleParameters, function (parameter) {
68507                             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));
68508                         });
68509                         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)); });
68510                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68511                         return true;
68512                     }
68513                 }
68514             }
68515             return false;
68516         }
68517         function checkGrammarFunctionLikeDeclaration(node) {
68518             // Prevent cascading error by short-circuit
68519             var file = ts.getSourceFileOfNode(node);
68520             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68521                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68522                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68523         }
68524         function checkGrammarClassLikeDeclaration(node) {
68525             var file = ts.getSourceFileOfNode(node);
68526             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68527         }
68528         function checkGrammarArrowFunction(node, file) {
68529             if (!ts.isArrowFunction(node)) {
68530                 return false;
68531             }
68532             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68533             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68534             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68535             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68536         }
68537         function checkGrammarIndexSignatureParameters(node) {
68538             var parameter = node.parameters[0];
68539             if (node.parameters.length !== 1) {
68540                 if (parameter) {
68541                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68542                 }
68543                 else {
68544                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68545                 }
68546             }
68547             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68548             if (parameter.dotDotDotToken) {
68549                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68550             }
68551             if (ts.hasModifiers(parameter)) {
68552                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68553             }
68554             if (parameter.questionToken) {
68555                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68556             }
68557             if (parameter.initializer) {
68558                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68559             }
68560             if (!parameter.type) {
68561                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68562             }
68563             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68564                 var type = getTypeFromTypeNode(parameter.type);
68565                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68566                     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));
68567                 }
68568                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68569                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68570                 }
68571                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68572             }
68573             if (!node.type) {
68574                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68575             }
68576             return false;
68577         }
68578         function checkGrammarIndexSignature(node) {
68579             // Prevent cascading error by short-circuit
68580             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68581         }
68582         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68583             if (typeArguments && typeArguments.length === 0) {
68584                 var sourceFile = ts.getSourceFileOfNode(node);
68585                 var start = typeArguments.pos - "<".length;
68586                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68587                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68588             }
68589             return false;
68590         }
68591         function checkGrammarTypeArguments(node, typeArguments) {
68592             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68593                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68594         }
68595         function checkGrammarTaggedTemplateChain(node) {
68596             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68597                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68598             }
68599             return false;
68600         }
68601         function checkGrammarForOmittedArgument(args) {
68602             if (args) {
68603                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68604                     var arg = args_4[_i];
68605                     if (arg.kind === 215 /* OmittedExpression */) {
68606                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68607                     }
68608                 }
68609             }
68610             return false;
68611         }
68612         function checkGrammarArguments(args) {
68613             return checkGrammarForOmittedArgument(args);
68614         }
68615         function checkGrammarHeritageClause(node) {
68616             var types = node.types;
68617             if (checkGrammarForDisallowedTrailingComma(types)) {
68618                 return true;
68619             }
68620             if (types && types.length === 0) {
68621                 var listType = ts.tokenToString(node.token);
68622                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68623             }
68624             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68625         }
68626         function checkGrammarExpressionWithTypeArguments(node) {
68627             return checkGrammarTypeArguments(node, node.typeArguments);
68628         }
68629         function checkGrammarClassDeclarationHeritageClauses(node) {
68630             var seenExtendsClause = false;
68631             var seenImplementsClause = false;
68632             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68633                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68634                     var heritageClause = _a[_i];
68635                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68636                         if (seenExtendsClause) {
68637                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68638                         }
68639                         if (seenImplementsClause) {
68640                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68641                         }
68642                         if (heritageClause.types.length > 1) {
68643                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68644                         }
68645                         seenExtendsClause = true;
68646                     }
68647                     else {
68648                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68649                         if (seenImplementsClause) {
68650                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68651                         }
68652                         seenImplementsClause = true;
68653                     }
68654                     // Grammar checking heritageClause inside class declaration
68655                     checkGrammarHeritageClause(heritageClause);
68656                 }
68657             }
68658         }
68659         function checkGrammarInterfaceDeclaration(node) {
68660             var seenExtendsClause = false;
68661             if (node.heritageClauses) {
68662                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68663                     var heritageClause = _a[_i];
68664                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68665                         if (seenExtendsClause) {
68666                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68667                         }
68668                         seenExtendsClause = true;
68669                     }
68670                     else {
68671                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68672                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68673                     }
68674                     // Grammar checking heritageClause inside class declaration
68675                     checkGrammarHeritageClause(heritageClause);
68676                 }
68677             }
68678             return false;
68679         }
68680         function checkGrammarComputedPropertyName(node) {
68681             // If node is not a computedPropertyName, just skip the grammar checking
68682             if (node.kind !== 154 /* ComputedPropertyName */) {
68683                 return false;
68684             }
68685             var computedPropertyName = node;
68686             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68687                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68688             }
68689             return false;
68690         }
68691         function checkGrammarForGenerator(node) {
68692             if (node.asteriskToken) {
68693                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68694                     node.kind === 201 /* FunctionExpression */ ||
68695                     node.kind === 161 /* MethodDeclaration */);
68696                 if (node.flags & 8388608 /* Ambient */) {
68697                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68698                 }
68699                 if (!node.body) {
68700                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68701                 }
68702             }
68703         }
68704         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68705             return !!questionToken && grammarErrorOnNode(questionToken, message);
68706         }
68707         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68708             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68709         }
68710         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68711             var seen = ts.createUnderscoreEscapedMap();
68712             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68713                 var prop = _a[_i];
68714                 if (prop.kind === 283 /* SpreadAssignment */) {
68715                     if (inDestructuring) {
68716                         // a rest property cannot be destructured any further
68717                         var expression = ts.skipParentheses(prop.expression);
68718                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68719                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68720                         }
68721                     }
68722                     continue;
68723                 }
68724                 var name = prop.name;
68725                 if (name.kind === 154 /* ComputedPropertyName */) {
68726                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68727                     checkGrammarComputedPropertyName(name);
68728                 }
68729                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68730                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68731                     // outside of destructuring it is a syntax error
68732                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68733                 }
68734                 if (name.kind === 76 /* PrivateIdentifier */) {
68735                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68736                 }
68737                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68738                 if (prop.modifiers) {
68739                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68740                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68741                         var mod = _c[_b];
68742                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68743                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68744                         }
68745                     }
68746                 }
68747                 // ECMA-262 11.1.5 Object Initializer
68748                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68749                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68750                 // IsDataDescriptor(propId.descriptor) is true.
68751                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68752                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68753                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68754                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68755                 var currentKind = void 0;
68756                 switch (prop.kind) {
68757                     case 282 /* ShorthandPropertyAssignment */:
68758                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68759                     // falls through
68760                     case 281 /* PropertyAssignment */:
68761                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68762                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68763                         if (name.kind === 8 /* NumericLiteral */) {
68764                             checkGrammarNumericLiteral(name);
68765                         }
68766                         currentKind = 4 /* PropertyAssignment */;
68767                         break;
68768                     case 161 /* MethodDeclaration */:
68769                         currentKind = 8 /* Method */;
68770                         break;
68771                     case 163 /* GetAccessor */:
68772                         currentKind = 1 /* GetAccessor */;
68773                         break;
68774                     case 164 /* SetAccessor */:
68775                         currentKind = 2 /* SetAccessor */;
68776                         break;
68777                     default:
68778                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68779                 }
68780                 if (!inDestructuring) {
68781                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68782                     if (effectiveName === undefined) {
68783                         continue;
68784                     }
68785                     var existingKind = seen.get(effectiveName);
68786                     if (!existingKind) {
68787                         seen.set(effectiveName, currentKind);
68788                     }
68789                     else {
68790                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68791                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68792                         }
68793                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68794                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68795                                 seen.set(effectiveName, currentKind | existingKind);
68796                             }
68797                             else {
68798                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68799                             }
68800                         }
68801                         else {
68802                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68803                         }
68804                     }
68805                 }
68806             }
68807         }
68808         function checkGrammarJsxElement(node) {
68809             checkGrammarTypeArguments(node, node.typeArguments);
68810             var seen = ts.createUnderscoreEscapedMap();
68811             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68812                 var attr = _a[_i];
68813                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68814                     continue;
68815                 }
68816                 var name = attr.name, initializer = attr.initializer;
68817                 if (!seen.get(name.escapedText)) {
68818                     seen.set(name.escapedText, true);
68819                 }
68820                 else {
68821                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
68822                 }
68823                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
68824                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
68825                 }
68826             }
68827         }
68828         function checkGrammarJsxExpression(node) {
68829             if (node.expression && ts.isCommaSequence(node.expression)) {
68830                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
68831             }
68832         }
68833         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
68834             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
68835                 return true;
68836             }
68837             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
68838                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
68839                     // use of 'for-await-of' in non-async function
68840                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
68841                     if (!hasParseDiagnostics(sourceFile)) {
68842                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
68843                         var func = ts.getContainingFunction(forInOrOfStatement);
68844                         if (func && func.kind !== 162 /* Constructor */) {
68845                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
68846                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68847                             ts.addRelatedInfo(diagnostic, relatedInfo);
68848                         }
68849                         diagnostics.add(diagnostic);
68850                         return true;
68851                     }
68852                     return false;
68853                 }
68854             }
68855             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
68856                 var variableList = forInOrOfStatement.initializer;
68857                 if (!checkGrammarVariableDeclarationList(variableList)) {
68858                     var declarations = variableList.declarations;
68859                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
68860                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
68861                     // For example:
68862                     //      var let = 10;
68863                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
68864                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
68865                     // We will then want to skip on grammar checking on variableList declaration
68866                     if (!declarations.length) {
68867                         return false;
68868                     }
68869                     if (declarations.length > 1) {
68870                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68871                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
68872                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
68873                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
68874                     }
68875                     var firstDeclaration = declarations[0];
68876                     if (firstDeclaration.initializer) {
68877                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68878                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
68879                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
68880                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
68881                     }
68882                     if (firstDeclaration.type) {
68883                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68884                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
68885                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
68886                         return grammarErrorOnNode(firstDeclaration, diagnostic);
68887                     }
68888                 }
68889             }
68890             return false;
68891         }
68892         function checkGrammarAccessor(accessor) {
68893             if (!(accessor.flags & 8388608 /* Ambient */)) {
68894                 if (languageVersion < 1 /* ES5 */) {
68895                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
68896                 }
68897                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
68898                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
68899                 }
68900             }
68901             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
68902                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
68903             }
68904             if (accessor.typeParameters) {
68905                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
68906             }
68907             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
68908                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
68909                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
68910                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
68911             }
68912             if (accessor.kind === 164 /* SetAccessor */) {
68913                 if (accessor.type) {
68914                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
68915                 }
68916                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
68917                 if (parameter.dotDotDotToken) {
68918                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
68919                 }
68920                 if (parameter.questionToken) {
68921                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
68922                 }
68923                 if (parameter.initializer) {
68924                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
68925                 }
68926             }
68927             return false;
68928         }
68929         /** Does the accessor have the right number of parameters?
68930          * A get accessor has no parameters or a single `this` parameter.
68931          * A set accessor has one parameter or a `this` parameter and one more parameter.
68932          */
68933         function doesAccessorHaveCorrectParameterCount(accessor) {
68934             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
68935         }
68936         function getAccessorThisParameter(accessor) {
68937             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
68938                 return ts.getThisParameter(accessor);
68939             }
68940         }
68941         function checkGrammarTypeOperatorNode(node) {
68942             if (node.operator === 147 /* UniqueKeyword */) {
68943                 if (node.type.kind !== 144 /* SymbolKeyword */) {
68944                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
68945                 }
68946                 var parent = ts.walkUpParenthesizedTypes(node.parent);
68947                 switch (parent.kind) {
68948                     case 242 /* VariableDeclaration */:
68949                         var decl = parent;
68950                         if (decl.name.kind !== 75 /* Identifier */) {
68951                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
68952                         }
68953                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
68954                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
68955                         }
68956                         if (!(decl.parent.flags & 2 /* Const */)) {
68957                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
68958                         }
68959                         break;
68960                     case 159 /* PropertyDeclaration */:
68961                         if (!ts.hasModifier(parent, 32 /* Static */) ||
68962                             !ts.hasModifier(parent, 64 /* Readonly */)) {
68963                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
68964                         }
68965                         break;
68966                     case 158 /* PropertySignature */:
68967                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
68968                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
68969                         }
68970                         break;
68971                     default:
68972                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
68973                 }
68974             }
68975             else if (node.operator === 138 /* ReadonlyKeyword */) {
68976                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
68977                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
68978                 }
68979             }
68980         }
68981         function checkGrammarForInvalidDynamicName(node, message) {
68982             if (isNonBindableDynamicName(node)) {
68983                 return grammarErrorOnNode(node, message);
68984             }
68985         }
68986         function checkGrammarMethod(node) {
68987             if (checkGrammarFunctionLikeDeclaration(node)) {
68988                 return true;
68989             }
68990             if (node.kind === 161 /* MethodDeclaration */) {
68991                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
68992                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
68993                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
68994                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
68995                     }
68996                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
68997                         return true;
68998                     }
68999                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69000                         return true;
69001                     }
69002                     else if (node.body === undefined) {
69003                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69004                     }
69005                 }
69006                 if (checkGrammarForGenerator(node)) {
69007                     return true;
69008                 }
69009             }
69010             if (ts.isClassLike(node.parent)) {
69011                 // Technically, computed properties in ambient contexts is disallowed
69012                 // for property declarations and accessors too, not just methods.
69013                 // However, property declarations disallow computed names in general,
69014                 // and accessors are not allowed in ambient contexts in general,
69015                 // so this error only really matters for methods.
69016                 if (node.flags & 8388608 /* Ambient */) {
69017                     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);
69018                 }
69019                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69020                     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);
69021                 }
69022             }
69023             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69024                 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);
69025             }
69026             else if (node.parent.kind === 173 /* TypeLiteral */) {
69027                 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);
69028             }
69029         }
69030         function checkGrammarBreakOrContinueStatement(node) {
69031             var current = node;
69032             while (current) {
69033                 if (ts.isFunctionLike(current)) {
69034                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69035                 }
69036                 switch (current.kind) {
69037                     case 238 /* LabeledStatement */:
69038                         if (node.label && current.label.escapedText === node.label.escapedText) {
69039                             // found matching label - verify that label usage is correct
69040                             // continue can only target labels that are on iteration statements
69041                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69042                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69043                             if (isMisplacedContinueLabel) {
69044                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69045                             }
69046                             return false;
69047                         }
69048                         break;
69049                     case 237 /* SwitchStatement */:
69050                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69051                             // unlabeled break within switch statement - ok
69052                             return false;
69053                         }
69054                         break;
69055                     default:
69056                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69057                             // unlabeled break or continue within iteration statement - ok
69058                             return false;
69059                         }
69060                         break;
69061                 }
69062                 current = current.parent;
69063             }
69064             if (node.label) {
69065                 var message = node.kind === 234 /* BreakStatement */
69066                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69067                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69068                 return grammarErrorOnNode(node, message);
69069             }
69070             else {
69071                 var message = node.kind === 234 /* BreakStatement */
69072                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69073                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69074                 return grammarErrorOnNode(node, message);
69075             }
69076         }
69077         function checkGrammarBindingElement(node) {
69078             if (node.dotDotDotToken) {
69079                 var elements = node.parent.elements;
69080                 if (node !== ts.last(elements)) {
69081                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69082                 }
69083                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69084                 if (node.propertyName) {
69085                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69086                 }
69087                 if (node.initializer) {
69088                     // Error on equals token which immediately precedes the initializer
69089                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69090                 }
69091             }
69092         }
69093         function isStringOrNumberLiteralExpression(expr) {
69094             return ts.isStringOrNumericLiteralLike(expr) ||
69095                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69096                     expr.operand.kind === 8 /* NumericLiteral */;
69097         }
69098         function isBigIntLiteralExpression(expr) {
69099             return expr.kind === 9 /* BigIntLiteral */ ||
69100                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69101                     expr.operand.kind === 9 /* BigIntLiteral */;
69102         }
69103         function isSimpleLiteralEnumReference(expr) {
69104             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69105                 ts.isEntityNameExpression(expr.expression)) {
69106                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69107             }
69108         }
69109         function checkAmbientInitializer(node) {
69110             var initializer = node.initializer;
69111             if (initializer) {
69112                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69113                     isSimpleLiteralEnumReference(initializer) ||
69114                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69115                     isBigIntLiteralExpression(initializer));
69116                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69117                 if (isConstOrReadonly && !node.type) {
69118                     if (isInvalidInitializer) {
69119                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69120                     }
69121                 }
69122                 else {
69123                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69124                 }
69125                 if (!isConstOrReadonly || isInvalidInitializer) {
69126                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69127                 }
69128             }
69129         }
69130         function checkGrammarVariableDeclaration(node) {
69131             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69132                 if (node.flags & 8388608 /* Ambient */) {
69133                     checkAmbientInitializer(node);
69134                 }
69135                 else if (!node.initializer) {
69136                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69137                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69138                     }
69139                     if (ts.isVarConst(node)) {
69140                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69141                     }
69142                 }
69143             }
69144             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69145                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69146             }
69147             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69148             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69149                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69150                 checkESModuleMarker(node.name);
69151             }
69152             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69153             // 1. LexicalDeclaration : LetOrConst BindingList ;
69154             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69155             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69156             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69157             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69158             // and its Identifier is eval or arguments
69159             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69160         }
69161         function checkESModuleMarker(name) {
69162             if (name.kind === 75 /* Identifier */) {
69163                 if (ts.idText(name) === "__esModule") {
69164                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69165                 }
69166             }
69167             else {
69168                 var elements = name.elements;
69169                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69170                     var element = elements_1[_i];
69171                     if (!ts.isOmittedExpression(element)) {
69172                         return checkESModuleMarker(element.name);
69173                     }
69174                 }
69175             }
69176             return false;
69177         }
69178         function checkGrammarNameInLetOrConstDeclarations(name) {
69179             if (name.kind === 75 /* Identifier */) {
69180                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69181                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69182                 }
69183             }
69184             else {
69185                 var elements = name.elements;
69186                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69187                     var element = elements_2[_i];
69188                     if (!ts.isOmittedExpression(element)) {
69189                         checkGrammarNameInLetOrConstDeclarations(element.name);
69190                     }
69191                 }
69192             }
69193             return false;
69194         }
69195         function checkGrammarVariableDeclarationList(declarationList) {
69196             var declarations = declarationList.declarations;
69197             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69198                 return true;
69199             }
69200             if (!declarationList.declarations.length) {
69201                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69202             }
69203             return false;
69204         }
69205         function allowLetAndConstDeclarations(parent) {
69206             switch (parent.kind) {
69207                 case 227 /* IfStatement */:
69208                 case 228 /* DoStatement */:
69209                 case 229 /* WhileStatement */:
69210                 case 236 /* WithStatement */:
69211                 case 230 /* ForStatement */:
69212                 case 231 /* ForInStatement */:
69213                 case 232 /* ForOfStatement */:
69214                     return false;
69215                 case 238 /* LabeledStatement */:
69216                     return allowLetAndConstDeclarations(parent.parent);
69217             }
69218             return true;
69219         }
69220         function checkGrammarForDisallowedLetOrConstStatement(node) {
69221             if (!allowLetAndConstDeclarations(node.parent)) {
69222                 if (ts.isLet(node.declarationList)) {
69223                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69224                 }
69225                 else if (ts.isVarConst(node.declarationList)) {
69226                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69227                 }
69228             }
69229         }
69230         function checkGrammarMetaProperty(node) {
69231             var escapedText = node.name.escapedText;
69232             switch (node.keywordToken) {
69233                 case 99 /* NewKeyword */:
69234                     if (escapedText !== "target") {
69235                         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");
69236                     }
69237                     break;
69238                 case 96 /* ImportKeyword */:
69239                     if (escapedText !== "meta") {
69240                         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");
69241                     }
69242                     break;
69243             }
69244         }
69245         function hasParseDiagnostics(sourceFile) {
69246             return sourceFile.parseDiagnostics.length > 0;
69247         }
69248         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69249             var sourceFile = ts.getSourceFileOfNode(node);
69250             if (!hasParseDiagnostics(sourceFile)) {
69251                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69252                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69253                 return true;
69254             }
69255             return false;
69256         }
69257         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69258             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69259             if (!hasParseDiagnostics(sourceFile)) {
69260                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69261                 return true;
69262             }
69263             return false;
69264         }
69265         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69266             var sourceFile = ts.getSourceFileOfNode(node);
69267             if (!hasParseDiagnostics(sourceFile)) {
69268                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69269                 return true;
69270             }
69271             return false;
69272         }
69273         function checkGrammarConstructorTypeParameters(node) {
69274             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69275             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69276             if (range) {
69277                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69278                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69279             }
69280         }
69281         function checkGrammarConstructorTypeAnnotation(node) {
69282             var type = ts.getEffectiveReturnTypeNode(node);
69283             if (type) {
69284                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69285             }
69286         }
69287         function checkGrammarProperty(node) {
69288             if (ts.isClassLike(node.parent)) {
69289                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69290                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69291                 }
69292                 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)) {
69293                     return true;
69294                 }
69295                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69296                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69297                 }
69298             }
69299             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69300                 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)) {
69301                     return true;
69302                 }
69303                 if (node.initializer) {
69304                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69305                 }
69306             }
69307             else if (node.parent.kind === 173 /* TypeLiteral */) {
69308                 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)) {
69309                     return true;
69310                 }
69311                 if (node.initializer) {
69312                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69313                 }
69314             }
69315             if (node.flags & 8388608 /* Ambient */) {
69316                 checkAmbientInitializer(node);
69317             }
69318             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69319                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69320                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69321             }
69322         }
69323         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69324             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69325             // interfaces and imports categories:
69326             //
69327             //  DeclarationElement:
69328             //     ExportAssignment
69329             //     export_opt   InterfaceDeclaration
69330             //     export_opt   TypeAliasDeclaration
69331             //     export_opt   ImportDeclaration
69332             //     export_opt   ExternalImportDeclaration
69333             //     export_opt   AmbientDeclaration
69334             //
69335             // TODO: The spec needs to be amended to reflect this grammar.
69336             if (node.kind === 246 /* InterfaceDeclaration */ ||
69337                 node.kind === 247 /* TypeAliasDeclaration */ ||
69338                 node.kind === 254 /* ImportDeclaration */ ||
69339                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69340                 node.kind === 260 /* ExportDeclaration */ ||
69341                 node.kind === 259 /* ExportAssignment */ ||
69342                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69343                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69344                 return false;
69345             }
69346             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69347         }
69348         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69349             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69350                 var decl = _a[_i];
69351                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69352                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69353                         return true;
69354                     }
69355                 }
69356             }
69357             return false;
69358         }
69359         function checkGrammarSourceFile(node) {
69360             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69361         }
69362         function checkGrammarStatementInAmbientContext(node) {
69363             if (node.flags & 8388608 /* Ambient */) {
69364                 // Find containing block which is either Block, ModuleBlock, SourceFile
69365                 var links = getNodeLinks(node);
69366                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69367                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69368                 }
69369                 // We are either parented by another statement, or some sort of block.
69370                 // If we're in a block, we only want to really report an error once
69371                 // to prevent noisiness.  So use a bit on the block to indicate if
69372                 // this has already been reported, and don't report if it has.
69373                 //
69374                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69375                     var links_2 = getNodeLinks(node.parent);
69376                     // Check if the containing block ever report this error
69377                     if (!links_2.hasReportedStatementInAmbientContext) {
69378                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69379                     }
69380                 }
69381                 else {
69382                     // We must be parented by a statement.  If so, there's no need
69383                     // to report the error as our parent will have already done it.
69384                     // Debug.assert(isStatement(node.parent));
69385                 }
69386             }
69387             return false;
69388         }
69389         function checkGrammarNumericLiteral(node) {
69390             // Grammar checking
69391             if (node.numericLiteralFlags & 32 /* Octal */) {
69392                 var diagnosticMessage = void 0;
69393                 if (languageVersion >= 1 /* ES5 */) {
69394                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69395                 }
69396                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69397                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69398                 }
69399                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69400                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69401                 }
69402                 if (diagnosticMessage) {
69403                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69404                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69405                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69406                 }
69407             }
69408             // Realism (size) checking
69409             checkNumericLiteralValueSize(node);
69410             return false;
69411         }
69412         function checkNumericLiteralValueSize(node) {
69413             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69414             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69415             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69416             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69417                 return;
69418             }
69419             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69420             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69421             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69422             // it's likely addition operations on it will fail too
69423             var apparentValue = +ts.getTextOfNode(node);
69424             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69425                 return;
69426             }
69427             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));
69428         }
69429         function checkGrammarBigIntLiteral(node) {
69430             var literalType = ts.isLiteralTypeNode(node.parent) ||
69431                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69432             if (!literalType) {
69433                 if (languageVersion < 7 /* ES2020 */) {
69434                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69435                         return true;
69436                     }
69437                 }
69438             }
69439             return false;
69440         }
69441         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69442             var sourceFile = ts.getSourceFileOfNode(node);
69443             if (!hasParseDiagnostics(sourceFile)) {
69444                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69445                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69446                 return true;
69447             }
69448             return false;
69449         }
69450         function getAmbientModules() {
69451             if (!ambientModulesCache) {
69452                 ambientModulesCache = [];
69453                 globals.forEach(function (global, sym) {
69454                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69455                     if (ambientModuleSymbolRegex.test(sym)) {
69456                         ambientModulesCache.push(global);
69457                     }
69458                 });
69459             }
69460             return ambientModulesCache;
69461         }
69462         function checkGrammarImportClause(node) {
69463             if (node.isTypeOnly && node.name && node.namedBindings) {
69464                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69465             }
69466             return false;
69467         }
69468         function checkGrammarImportCallExpression(node) {
69469             if (moduleKind === ts.ModuleKind.ES2015) {
69470                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69471             }
69472             if (node.typeArguments) {
69473                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69474             }
69475             var nodeArguments = node.arguments;
69476             if (nodeArguments.length !== 1) {
69477                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69478             }
69479             checkGrammarForDisallowedTrailingComma(nodeArguments);
69480             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69481             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69482             if (ts.isSpreadElement(nodeArguments[0])) {
69483                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69484             }
69485             return false;
69486         }
69487         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69488             var sourceObjectFlags = ts.getObjectFlags(source);
69489             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69490                 return ts.find(unionTarget.types, function (target) {
69491                     if (target.flags & 524288 /* Object */) {
69492                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69493                         if (overlapObjFlags & 4 /* Reference */) {
69494                             return source.target === target.target;
69495                         }
69496                         if (overlapObjFlags & 16 /* Anonymous */) {
69497                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69498                         }
69499                     }
69500                     return false;
69501                 });
69502             }
69503         }
69504         function findBestTypeForObjectLiteral(source, unionTarget) {
69505             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69506                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69507             }
69508         }
69509         function findBestTypeForInvokable(source, unionTarget) {
69510             var signatureKind = 0 /* Call */;
69511             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69512                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69513             if (hasSignatures) {
69514                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69515             }
69516         }
69517         function findMostOverlappyType(source, unionTarget) {
69518             var bestMatch;
69519             var matchingCount = 0;
69520             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69521                 var target = _a[_i];
69522                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69523                 if (overlap.flags & 4194304 /* Index */) {
69524                     // perfect overlap of keys
69525                     bestMatch = target;
69526                     matchingCount = Infinity;
69527                 }
69528                 else if (overlap.flags & 1048576 /* Union */) {
69529                     // We only want to account for literal types otherwise.
69530                     // If we have a union of index types, it seems likely that we
69531                     // needed to elaborate between two generic mapped types anyway.
69532                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69533                     if (len >= matchingCount) {
69534                         bestMatch = target;
69535                         matchingCount = len;
69536                     }
69537                 }
69538                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69539                     bestMatch = target;
69540                     matchingCount = 1;
69541                 }
69542             }
69543             return bestMatch;
69544         }
69545         function filterPrimitivesIfContainsNonPrimitive(type) {
69546             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69547                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69548                 if (!(result.flags & 131072 /* Never */)) {
69549                     return result;
69550                 }
69551             }
69552             return type;
69553         }
69554         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69555         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69556             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69557                 var sourceProperties = getPropertiesOfType(source);
69558                 if (sourceProperties) {
69559                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69560                     if (sourcePropertiesFiltered) {
69561                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69562                     }
69563                 }
69564             }
69565             return undefined;
69566         }
69567     }
69568     ts.createTypeChecker = createTypeChecker;
69569     function isNotAccessor(declaration) {
69570         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69571         return !ts.isAccessor(declaration);
69572     }
69573     function isNotOverload(declaration) {
69574         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69575             !!declaration.body;
69576     }
69577     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69578     function isDeclarationNameOrImportPropertyName(name) {
69579         switch (name.parent.kind) {
69580             case 258 /* ImportSpecifier */:
69581             case 263 /* ExportSpecifier */:
69582                 return ts.isIdentifier(name);
69583             default:
69584                 return ts.isDeclarationName(name);
69585         }
69586     }
69587     function isSomeImportDeclaration(decl) {
69588         switch (decl.kind) {
69589             case 255 /* ImportClause */: // For default import
69590             case 253 /* ImportEqualsDeclaration */:
69591             case 256 /* NamespaceImport */:
69592             case 258 /* ImportSpecifier */: // For rename import `x as y`
69593                 return true;
69594             case 75 /* Identifier */:
69595                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69596                 return decl.parent.kind === 258 /* ImportSpecifier */;
69597             default:
69598                 return false;
69599         }
69600     }
69601     var JsxNames;
69602     (function (JsxNames) {
69603         JsxNames.JSX = "JSX";
69604         JsxNames.IntrinsicElements = "IntrinsicElements";
69605         JsxNames.ElementClass = "ElementClass";
69606         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69607         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69608         JsxNames.Element = "Element";
69609         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69610         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69611         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69612     })(JsxNames || (JsxNames = {}));
69613     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69614         switch (typeKind) {
69615             case 0 /* Yield */: return "yieldType";
69616             case 1 /* Return */: return "returnType";
69617             case 2 /* Next */: return "nextType";
69618         }
69619     }
69620     function signatureHasRestParameter(s) {
69621         return !!(s.flags & 1 /* HasRestParameter */);
69622     }
69623     ts.signatureHasRestParameter = signatureHasRestParameter;
69624     function signatureHasLiteralTypes(s) {
69625         return !!(s.flags & 2 /* HasLiteralTypes */);
69626     }
69627     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69628 })(ts || (ts = {}));
69629 var ts;
69630 (function (ts) {
69631     function createSynthesizedNode(kind) {
69632         var node = ts.createNode(kind, -1, -1);
69633         node.flags |= 8 /* Synthesized */;
69634         return node;
69635     }
69636     /* @internal */
69637     function updateNode(updated, original) {
69638         if (updated !== original) {
69639             setOriginalNode(updated, original);
69640             setTextRange(updated, original);
69641             ts.aggregateTransformFlags(updated);
69642         }
69643         return updated;
69644     }
69645     ts.updateNode = updateNode;
69646     /**
69647      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69648      */
69649     function createNodeArray(elements, hasTrailingComma) {
69650         if (!elements || elements === ts.emptyArray) {
69651             elements = [];
69652         }
69653         else if (ts.isNodeArray(elements)) {
69654             return elements;
69655         }
69656         var array = elements;
69657         array.pos = -1;
69658         array.end = -1;
69659         array.hasTrailingComma = hasTrailingComma;
69660         return array;
69661     }
69662     ts.createNodeArray = createNodeArray;
69663     /**
69664      * Creates a shallow, memberwise clone of a node with no source map location.
69665      */
69666     /* @internal */
69667     function getSynthesizedClone(node) {
69668         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69669         // the original node. We also need to exclude specific properties and only include own-
69670         // properties (to skip members already defined on the shared prototype).
69671         if (node === undefined) {
69672             return node;
69673         }
69674         var clone = createSynthesizedNode(node.kind);
69675         clone.flags |= node.flags;
69676         setOriginalNode(clone, node);
69677         for (var key in node) {
69678             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69679                 continue;
69680             }
69681             clone[key] = node[key];
69682         }
69683         return clone;
69684     }
69685     ts.getSynthesizedClone = getSynthesizedClone;
69686     function createLiteral(value, isSingleQuote) {
69687         if (typeof value === "number") {
69688             return createNumericLiteral(value + "");
69689         }
69690         // eslint-disable-next-line no-in-operator
69691         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69692             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69693         }
69694         if (typeof value === "boolean") {
69695             return value ? createTrue() : createFalse();
69696         }
69697         if (ts.isString(value)) {
69698             var res = createStringLiteral(value);
69699             if (isSingleQuote)
69700                 res.singleQuote = true;
69701             return res;
69702         }
69703         return createLiteralFromNode(value);
69704     }
69705     ts.createLiteral = createLiteral;
69706     function createNumericLiteral(value, numericLiteralFlags) {
69707         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69708         var node = createSynthesizedNode(8 /* NumericLiteral */);
69709         node.text = value;
69710         node.numericLiteralFlags = numericLiteralFlags;
69711         return node;
69712     }
69713     ts.createNumericLiteral = createNumericLiteral;
69714     function createBigIntLiteral(value) {
69715         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69716         node.text = value;
69717         return node;
69718     }
69719     ts.createBigIntLiteral = createBigIntLiteral;
69720     function createStringLiteral(text) {
69721         var node = createSynthesizedNode(10 /* StringLiteral */);
69722         node.text = text;
69723         return node;
69724     }
69725     ts.createStringLiteral = createStringLiteral;
69726     function createRegularExpressionLiteral(text) {
69727         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69728         node.text = text;
69729         return node;
69730     }
69731     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69732     function createLiteralFromNode(sourceNode) {
69733         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69734         node.textSourceNode = sourceNode;
69735         return node;
69736     }
69737     function createIdentifier(text, typeArguments) {
69738         var node = createSynthesizedNode(75 /* Identifier */);
69739         node.escapedText = ts.escapeLeadingUnderscores(text);
69740         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69741         node.autoGenerateFlags = 0 /* None */;
69742         node.autoGenerateId = 0;
69743         if (typeArguments) {
69744             node.typeArguments = createNodeArray(typeArguments);
69745         }
69746         return node;
69747     }
69748     ts.createIdentifier = createIdentifier;
69749     function updateIdentifier(node, typeArguments) {
69750         return node.typeArguments !== typeArguments
69751             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69752             : node;
69753     }
69754     ts.updateIdentifier = updateIdentifier;
69755     var nextAutoGenerateId = 0;
69756     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69757         var name = createIdentifier("");
69758         name.autoGenerateFlags = 1 /* Auto */;
69759         name.autoGenerateId = nextAutoGenerateId;
69760         nextAutoGenerateId++;
69761         if (recordTempVariable) {
69762             recordTempVariable(name);
69763         }
69764         if (reservedInNestedScopes) {
69765             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69766         }
69767         return name;
69768     }
69769     ts.createTempVariable = createTempVariable;
69770     /** Create a unique temporary variable for use in a loop. */
69771     function createLoopVariable() {
69772         var name = createIdentifier("");
69773         name.autoGenerateFlags = 2 /* Loop */;
69774         name.autoGenerateId = nextAutoGenerateId;
69775         nextAutoGenerateId++;
69776         return name;
69777     }
69778     ts.createLoopVariable = createLoopVariable;
69779     /** Create a unique name based on the supplied text. */
69780     function createUniqueName(text) {
69781         var name = createIdentifier(text);
69782         name.autoGenerateFlags = 3 /* Unique */;
69783         name.autoGenerateId = nextAutoGenerateId;
69784         nextAutoGenerateId++;
69785         return name;
69786     }
69787     ts.createUniqueName = createUniqueName;
69788     function createOptimisticUniqueName(text) {
69789         var name = createIdentifier(text);
69790         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69791         name.autoGenerateId = nextAutoGenerateId;
69792         nextAutoGenerateId++;
69793         return name;
69794     }
69795     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69796     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69797     function createFileLevelUniqueName(text) {
69798         var name = createOptimisticUniqueName(text);
69799         name.autoGenerateFlags |= 32 /* FileLevel */;
69800         return name;
69801     }
69802     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69803     function getGeneratedNameForNode(node, flags) {
69804         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69805         name.autoGenerateFlags = 4 /* Node */ | flags;
69806         name.autoGenerateId = nextAutoGenerateId;
69807         name.original = node;
69808         nextAutoGenerateId++;
69809         return name;
69810     }
69811     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69812     // Private Identifiers
69813     function createPrivateIdentifier(text) {
69814         if (text[0] !== "#") {
69815             ts.Debug.fail("First character of private identifier must be #: " + text);
69816         }
69817         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
69818         node.escapedText = ts.escapeLeadingUnderscores(text);
69819         return node;
69820     }
69821     ts.createPrivateIdentifier = createPrivateIdentifier;
69822     // Punctuation
69823     function createToken(token) {
69824         return createSynthesizedNode(token);
69825     }
69826     ts.createToken = createToken;
69827     // Reserved words
69828     function createSuper() {
69829         return createSynthesizedNode(102 /* SuperKeyword */);
69830     }
69831     ts.createSuper = createSuper;
69832     function createThis() {
69833         return createSynthesizedNode(104 /* ThisKeyword */);
69834     }
69835     ts.createThis = createThis;
69836     function createNull() {
69837         return createSynthesizedNode(100 /* NullKeyword */);
69838     }
69839     ts.createNull = createNull;
69840     function createTrue() {
69841         return createSynthesizedNode(106 /* TrueKeyword */);
69842     }
69843     ts.createTrue = createTrue;
69844     function createFalse() {
69845         return createSynthesizedNode(91 /* FalseKeyword */);
69846     }
69847     ts.createFalse = createFalse;
69848     // Modifiers
69849     function createModifier(kind) {
69850         return createToken(kind);
69851     }
69852     ts.createModifier = createModifier;
69853     function createModifiersFromModifierFlags(flags) {
69854         var result = [];
69855         if (flags & 1 /* Export */) {
69856             result.push(createModifier(89 /* ExportKeyword */));
69857         }
69858         if (flags & 2 /* Ambient */) {
69859             result.push(createModifier(130 /* DeclareKeyword */));
69860         }
69861         if (flags & 512 /* Default */) {
69862             result.push(createModifier(84 /* DefaultKeyword */));
69863         }
69864         if (flags & 2048 /* Const */) {
69865             result.push(createModifier(81 /* ConstKeyword */));
69866         }
69867         if (flags & 4 /* Public */) {
69868             result.push(createModifier(119 /* PublicKeyword */));
69869         }
69870         if (flags & 8 /* Private */) {
69871             result.push(createModifier(117 /* PrivateKeyword */));
69872         }
69873         if (flags & 16 /* Protected */) {
69874             result.push(createModifier(118 /* ProtectedKeyword */));
69875         }
69876         if (flags & 128 /* Abstract */) {
69877             result.push(createModifier(122 /* AbstractKeyword */));
69878         }
69879         if (flags & 32 /* Static */) {
69880             result.push(createModifier(120 /* StaticKeyword */));
69881         }
69882         if (flags & 64 /* Readonly */) {
69883             result.push(createModifier(138 /* ReadonlyKeyword */));
69884         }
69885         if (flags & 256 /* Async */) {
69886             result.push(createModifier(126 /* AsyncKeyword */));
69887         }
69888         return result;
69889     }
69890     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
69891     // Names
69892     function createQualifiedName(left, right) {
69893         var node = createSynthesizedNode(153 /* QualifiedName */);
69894         node.left = left;
69895         node.right = asName(right);
69896         return node;
69897     }
69898     ts.createQualifiedName = createQualifiedName;
69899     function updateQualifiedName(node, left, right) {
69900         return node.left !== left
69901             || node.right !== right
69902             ? updateNode(createQualifiedName(left, right), node)
69903             : node;
69904     }
69905     ts.updateQualifiedName = updateQualifiedName;
69906     function parenthesizeForComputedName(expression) {
69907         return ts.isCommaSequence(expression)
69908             ? createParen(expression)
69909             : expression;
69910     }
69911     function createComputedPropertyName(expression) {
69912         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
69913         node.expression = parenthesizeForComputedName(expression);
69914         return node;
69915     }
69916     ts.createComputedPropertyName = createComputedPropertyName;
69917     function updateComputedPropertyName(node, expression) {
69918         return node.expression !== expression
69919             ? updateNode(createComputedPropertyName(expression), node)
69920             : node;
69921     }
69922     ts.updateComputedPropertyName = updateComputedPropertyName;
69923     // Signature elements
69924     function createTypeParameterDeclaration(name, constraint, defaultType) {
69925         var node = createSynthesizedNode(155 /* TypeParameter */);
69926         node.name = asName(name);
69927         node.constraint = constraint;
69928         node.default = defaultType;
69929         return node;
69930     }
69931     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
69932     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
69933         return node.name !== name
69934             || node.constraint !== constraint
69935             || node.default !== defaultType
69936             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
69937             : node;
69938     }
69939     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
69940     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69941         var node = createSynthesizedNode(156 /* Parameter */);
69942         node.decorators = asNodeArray(decorators);
69943         node.modifiers = asNodeArray(modifiers);
69944         node.dotDotDotToken = dotDotDotToken;
69945         node.name = asName(name);
69946         node.questionToken = questionToken;
69947         node.type = type;
69948         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
69949         return node;
69950     }
69951     ts.createParameter = createParameter;
69952     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69953         return node.decorators !== decorators
69954             || node.modifiers !== modifiers
69955             || node.dotDotDotToken !== dotDotDotToken
69956             || node.name !== name
69957             || node.questionToken !== questionToken
69958             || node.type !== type
69959             || node.initializer !== initializer
69960             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
69961             : node;
69962     }
69963     ts.updateParameter = updateParameter;
69964     function createDecorator(expression) {
69965         var node = createSynthesizedNode(157 /* Decorator */);
69966         node.expression = ts.parenthesizeForAccess(expression);
69967         return node;
69968     }
69969     ts.createDecorator = createDecorator;
69970     function updateDecorator(node, expression) {
69971         return node.expression !== expression
69972             ? updateNode(createDecorator(expression), node)
69973             : node;
69974     }
69975     ts.updateDecorator = updateDecorator;
69976     // Type Elements
69977     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
69978         var node = createSynthesizedNode(158 /* PropertySignature */);
69979         node.modifiers = asNodeArray(modifiers);
69980         node.name = asName(name);
69981         node.questionToken = questionToken;
69982         node.type = type;
69983         node.initializer = initializer;
69984         return node;
69985     }
69986     ts.createPropertySignature = createPropertySignature;
69987     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
69988         return node.modifiers !== modifiers
69989             || node.name !== name
69990             || node.questionToken !== questionToken
69991             || node.type !== type
69992             || node.initializer !== initializer
69993             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
69994             : node;
69995     }
69996     ts.updatePropertySignature = updatePropertySignature;
69997     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
69998         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
69999         node.decorators = asNodeArray(decorators);
70000         node.modifiers = asNodeArray(modifiers);
70001         node.name = asName(name);
70002         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70003         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70004         node.type = type;
70005         node.initializer = initializer;
70006         return node;
70007     }
70008     ts.createProperty = createProperty;
70009     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70010         return node.decorators !== decorators
70011             || node.modifiers !== modifiers
70012             || node.name !== name
70013             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70014             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70015             || node.type !== type
70016             || node.initializer !== initializer
70017             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70018             : node;
70019     }
70020     ts.updateProperty = updateProperty;
70021     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70022         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70023         node.name = asName(name);
70024         node.questionToken = questionToken;
70025         return node;
70026     }
70027     ts.createMethodSignature = createMethodSignature;
70028     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70029         return node.typeParameters !== typeParameters
70030             || node.parameters !== parameters
70031             || node.type !== type
70032             || node.name !== name
70033             || node.questionToken !== questionToken
70034             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70035             : node;
70036     }
70037     ts.updateMethodSignature = updateMethodSignature;
70038     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70039         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70040         node.decorators = asNodeArray(decorators);
70041         node.modifiers = asNodeArray(modifiers);
70042         node.asteriskToken = asteriskToken;
70043         node.name = asName(name);
70044         node.questionToken = questionToken;
70045         node.typeParameters = asNodeArray(typeParameters);
70046         node.parameters = createNodeArray(parameters);
70047         node.type = type;
70048         node.body = body;
70049         return node;
70050     }
70051     ts.createMethod = createMethod;
70052     function createMethodCall(object, methodName, argumentsList) {
70053         return createCall(createPropertyAccess(object, asName(methodName)), 
70054         /*typeArguments*/ undefined, argumentsList);
70055     }
70056     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70057         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70058     }
70059     /* @internal */
70060     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70061         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70062     }
70063     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70064     function tryAddPropertyAssignment(properties, propertyName, expression) {
70065         if (expression) {
70066             properties.push(createPropertyAssignment(propertyName, expression));
70067             return true;
70068         }
70069         return false;
70070     }
70071     /* @internal */
70072     function createPropertyDescriptor(attributes, singleLine) {
70073         var properties = [];
70074         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70075         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70076         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70077         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70078         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70079         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70080         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70081         return createObjectLiteral(properties, !singleLine);
70082     }
70083     ts.createPropertyDescriptor = createPropertyDescriptor;
70084     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70085         return node.decorators !== decorators
70086             || node.modifiers !== modifiers
70087             || node.asteriskToken !== asteriskToken
70088             || node.name !== name
70089             || node.questionToken !== questionToken
70090             || node.typeParameters !== typeParameters
70091             || node.parameters !== parameters
70092             || node.type !== type
70093             || node.body !== body
70094             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70095             : node;
70096     }
70097     ts.updateMethod = updateMethod;
70098     function createConstructor(decorators, modifiers, parameters, body) {
70099         var node = createSynthesizedNode(162 /* Constructor */);
70100         node.decorators = asNodeArray(decorators);
70101         node.modifiers = asNodeArray(modifiers);
70102         node.typeParameters = undefined;
70103         node.parameters = createNodeArray(parameters);
70104         node.type = undefined;
70105         node.body = body;
70106         return node;
70107     }
70108     ts.createConstructor = createConstructor;
70109     function updateConstructor(node, decorators, modifiers, parameters, body) {
70110         return node.decorators !== decorators
70111             || node.modifiers !== modifiers
70112             || node.parameters !== parameters
70113             || node.body !== body
70114             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70115             : node;
70116     }
70117     ts.updateConstructor = updateConstructor;
70118     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70119         var node = createSynthesizedNode(163 /* GetAccessor */);
70120         node.decorators = asNodeArray(decorators);
70121         node.modifiers = asNodeArray(modifiers);
70122         node.name = asName(name);
70123         node.typeParameters = undefined;
70124         node.parameters = createNodeArray(parameters);
70125         node.type = type;
70126         node.body = body;
70127         return node;
70128     }
70129     ts.createGetAccessor = createGetAccessor;
70130     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70131         return node.decorators !== decorators
70132             || node.modifiers !== modifiers
70133             || node.name !== name
70134             || node.parameters !== parameters
70135             || node.type !== type
70136             || node.body !== body
70137             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70138             : node;
70139     }
70140     ts.updateGetAccessor = updateGetAccessor;
70141     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70142         var node = createSynthesizedNode(164 /* SetAccessor */);
70143         node.decorators = asNodeArray(decorators);
70144         node.modifiers = asNodeArray(modifiers);
70145         node.name = asName(name);
70146         node.typeParameters = undefined;
70147         node.parameters = createNodeArray(parameters);
70148         node.body = body;
70149         return node;
70150     }
70151     ts.createSetAccessor = createSetAccessor;
70152     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70153         return node.decorators !== decorators
70154             || node.modifiers !== modifiers
70155             || node.name !== name
70156             || node.parameters !== parameters
70157             || node.body !== body
70158             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70159             : node;
70160     }
70161     ts.updateSetAccessor = updateSetAccessor;
70162     function createCallSignature(typeParameters, parameters, type) {
70163         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70164     }
70165     ts.createCallSignature = createCallSignature;
70166     function updateCallSignature(node, typeParameters, parameters, type) {
70167         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70168     }
70169     ts.updateCallSignature = updateCallSignature;
70170     function createConstructSignature(typeParameters, parameters, type) {
70171         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70172     }
70173     ts.createConstructSignature = createConstructSignature;
70174     function updateConstructSignature(node, typeParameters, parameters, type) {
70175         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70176     }
70177     ts.updateConstructSignature = updateConstructSignature;
70178     function createIndexSignature(decorators, modifiers, parameters, type) {
70179         var node = createSynthesizedNode(167 /* IndexSignature */);
70180         node.decorators = asNodeArray(decorators);
70181         node.modifiers = asNodeArray(modifiers);
70182         node.parameters = createNodeArray(parameters);
70183         node.type = type;
70184         return node;
70185     }
70186     ts.createIndexSignature = createIndexSignature;
70187     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70188         return node.parameters !== parameters
70189             || node.type !== type
70190             || node.decorators !== decorators
70191             || node.modifiers !== modifiers
70192             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70193             : node;
70194     }
70195     ts.updateIndexSignature = updateIndexSignature;
70196     /* @internal */
70197     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70198         var node = createSynthesizedNode(kind);
70199         node.typeParameters = asNodeArray(typeParameters);
70200         node.parameters = asNodeArray(parameters);
70201         node.type = type;
70202         node.typeArguments = asNodeArray(typeArguments);
70203         return node;
70204     }
70205     ts.createSignatureDeclaration = createSignatureDeclaration;
70206     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70207         return node.typeParameters !== typeParameters
70208             || node.parameters !== parameters
70209             || node.type !== type
70210             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70211             : node;
70212     }
70213     // Types
70214     function createKeywordTypeNode(kind) {
70215         return createSynthesizedNode(kind);
70216     }
70217     ts.createKeywordTypeNode = createKeywordTypeNode;
70218     function createTypePredicateNode(parameterName, type) {
70219         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70220     }
70221     ts.createTypePredicateNode = createTypePredicateNode;
70222     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70223         var node = createSynthesizedNode(168 /* TypePredicate */);
70224         node.assertsModifier = assertsModifier;
70225         node.parameterName = asName(parameterName);
70226         node.type = type;
70227         return node;
70228     }
70229     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70230     function updateTypePredicateNode(node, parameterName, type) {
70231         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70232     }
70233     ts.updateTypePredicateNode = updateTypePredicateNode;
70234     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70235         return node.assertsModifier !== assertsModifier
70236             || node.parameterName !== parameterName
70237             || node.type !== type
70238             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70239             : node;
70240     }
70241     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70242     function createTypeReferenceNode(typeName, typeArguments) {
70243         var node = createSynthesizedNode(169 /* TypeReference */);
70244         node.typeName = asName(typeName);
70245         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70246         return node;
70247     }
70248     ts.createTypeReferenceNode = createTypeReferenceNode;
70249     function updateTypeReferenceNode(node, typeName, typeArguments) {
70250         return node.typeName !== typeName
70251             || node.typeArguments !== typeArguments
70252             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70253             : node;
70254     }
70255     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70256     function createFunctionTypeNode(typeParameters, parameters, type) {
70257         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70258     }
70259     ts.createFunctionTypeNode = createFunctionTypeNode;
70260     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70261         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70262     }
70263     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70264     function createConstructorTypeNode(typeParameters, parameters, type) {
70265         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70266     }
70267     ts.createConstructorTypeNode = createConstructorTypeNode;
70268     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70269         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70270     }
70271     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70272     function createTypeQueryNode(exprName) {
70273         var node = createSynthesizedNode(172 /* TypeQuery */);
70274         node.exprName = exprName;
70275         return node;
70276     }
70277     ts.createTypeQueryNode = createTypeQueryNode;
70278     function updateTypeQueryNode(node, exprName) {
70279         return node.exprName !== exprName
70280             ? updateNode(createTypeQueryNode(exprName), node)
70281             : node;
70282     }
70283     ts.updateTypeQueryNode = updateTypeQueryNode;
70284     function createTypeLiteralNode(members) {
70285         var node = createSynthesizedNode(173 /* TypeLiteral */);
70286         node.members = createNodeArray(members);
70287         return node;
70288     }
70289     ts.createTypeLiteralNode = createTypeLiteralNode;
70290     function updateTypeLiteralNode(node, members) {
70291         return node.members !== members
70292             ? updateNode(createTypeLiteralNode(members), node)
70293             : node;
70294     }
70295     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70296     function createArrayTypeNode(elementType) {
70297         var node = createSynthesizedNode(174 /* ArrayType */);
70298         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70299         return node;
70300     }
70301     ts.createArrayTypeNode = createArrayTypeNode;
70302     function updateArrayTypeNode(node, elementType) {
70303         return node.elementType !== elementType
70304             ? updateNode(createArrayTypeNode(elementType), node)
70305             : node;
70306     }
70307     ts.updateArrayTypeNode = updateArrayTypeNode;
70308     function createTupleTypeNode(elementTypes) {
70309         var node = createSynthesizedNode(175 /* TupleType */);
70310         node.elementTypes = createNodeArray(elementTypes);
70311         return node;
70312     }
70313     ts.createTupleTypeNode = createTupleTypeNode;
70314     function updateTupleTypeNode(node, elementTypes) {
70315         return node.elementTypes !== elementTypes
70316             ? updateNode(createTupleTypeNode(elementTypes), node)
70317             : node;
70318     }
70319     ts.updateTupleTypeNode = updateTupleTypeNode;
70320     function createOptionalTypeNode(type) {
70321         var node = createSynthesizedNode(176 /* OptionalType */);
70322         node.type = ts.parenthesizeArrayTypeMember(type);
70323         return node;
70324     }
70325     ts.createOptionalTypeNode = createOptionalTypeNode;
70326     function updateOptionalTypeNode(node, type) {
70327         return node.type !== type
70328             ? updateNode(createOptionalTypeNode(type), node)
70329             : node;
70330     }
70331     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70332     function createRestTypeNode(type) {
70333         var node = createSynthesizedNode(177 /* RestType */);
70334         node.type = type;
70335         return node;
70336     }
70337     ts.createRestTypeNode = createRestTypeNode;
70338     function updateRestTypeNode(node, type) {
70339         return node.type !== type
70340             ? updateNode(createRestTypeNode(type), node)
70341             : node;
70342     }
70343     ts.updateRestTypeNode = updateRestTypeNode;
70344     function createUnionTypeNode(types) {
70345         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70346     }
70347     ts.createUnionTypeNode = createUnionTypeNode;
70348     function updateUnionTypeNode(node, types) {
70349         return updateUnionOrIntersectionTypeNode(node, types);
70350     }
70351     ts.updateUnionTypeNode = updateUnionTypeNode;
70352     function createIntersectionTypeNode(types) {
70353         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70354     }
70355     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70356     function updateIntersectionTypeNode(node, types) {
70357         return updateUnionOrIntersectionTypeNode(node, types);
70358     }
70359     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70360     function createUnionOrIntersectionTypeNode(kind, types) {
70361         var node = createSynthesizedNode(kind);
70362         node.types = ts.parenthesizeElementTypeMembers(types);
70363         return node;
70364     }
70365     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70366     function updateUnionOrIntersectionTypeNode(node, types) {
70367         return node.types !== types
70368             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70369             : node;
70370     }
70371     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70372         var node = createSynthesizedNode(180 /* ConditionalType */);
70373         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70374         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70375         node.trueType = trueType;
70376         node.falseType = falseType;
70377         return node;
70378     }
70379     ts.createConditionalTypeNode = createConditionalTypeNode;
70380     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70381         return node.checkType !== checkType
70382             || node.extendsType !== extendsType
70383             || node.trueType !== trueType
70384             || node.falseType !== falseType
70385             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70386             : node;
70387     }
70388     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70389     function createInferTypeNode(typeParameter) {
70390         var node = createSynthesizedNode(181 /* InferType */);
70391         node.typeParameter = typeParameter;
70392         return node;
70393     }
70394     ts.createInferTypeNode = createInferTypeNode;
70395     function updateInferTypeNode(node, typeParameter) {
70396         return node.typeParameter !== typeParameter
70397             ? updateNode(createInferTypeNode(typeParameter), node)
70398             : node;
70399     }
70400     ts.updateInferTypeNode = updateInferTypeNode;
70401     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70402         var node = createSynthesizedNode(188 /* ImportType */);
70403         node.argument = argument;
70404         node.qualifier = qualifier;
70405         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70406         node.isTypeOf = isTypeOf;
70407         return node;
70408     }
70409     ts.createImportTypeNode = createImportTypeNode;
70410     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70411         return node.argument !== argument
70412             || node.qualifier !== qualifier
70413             || node.typeArguments !== typeArguments
70414             || node.isTypeOf !== isTypeOf
70415             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70416             : node;
70417     }
70418     ts.updateImportTypeNode = updateImportTypeNode;
70419     function createParenthesizedType(type) {
70420         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70421         node.type = type;
70422         return node;
70423     }
70424     ts.createParenthesizedType = createParenthesizedType;
70425     function updateParenthesizedType(node, type) {
70426         return node.type !== type
70427             ? updateNode(createParenthesizedType(type), node)
70428             : node;
70429     }
70430     ts.updateParenthesizedType = updateParenthesizedType;
70431     function createThisTypeNode() {
70432         return createSynthesizedNode(183 /* ThisType */);
70433     }
70434     ts.createThisTypeNode = createThisTypeNode;
70435     function createTypeOperatorNode(operatorOrType, type) {
70436         var node = createSynthesizedNode(184 /* TypeOperator */);
70437         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70438         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70439         return node;
70440     }
70441     ts.createTypeOperatorNode = createTypeOperatorNode;
70442     function updateTypeOperatorNode(node, type) {
70443         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70444     }
70445     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70446     function createIndexedAccessTypeNode(objectType, indexType) {
70447         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70448         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70449         node.indexType = indexType;
70450         return node;
70451     }
70452     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70453     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70454         return node.objectType !== objectType
70455             || node.indexType !== indexType
70456             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70457             : node;
70458     }
70459     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70460     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70461         var node = createSynthesizedNode(186 /* MappedType */);
70462         node.readonlyToken = readonlyToken;
70463         node.typeParameter = typeParameter;
70464         node.questionToken = questionToken;
70465         node.type = type;
70466         return node;
70467     }
70468     ts.createMappedTypeNode = createMappedTypeNode;
70469     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70470         return node.readonlyToken !== readonlyToken
70471             || node.typeParameter !== typeParameter
70472             || node.questionToken !== questionToken
70473             || node.type !== type
70474             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70475             : node;
70476     }
70477     ts.updateMappedTypeNode = updateMappedTypeNode;
70478     function createLiteralTypeNode(literal) {
70479         var node = createSynthesizedNode(187 /* LiteralType */);
70480         node.literal = literal;
70481         return node;
70482     }
70483     ts.createLiteralTypeNode = createLiteralTypeNode;
70484     function updateLiteralTypeNode(node, literal) {
70485         return node.literal !== literal
70486             ? updateNode(createLiteralTypeNode(literal), node)
70487             : node;
70488     }
70489     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70490     // Binding Patterns
70491     function createObjectBindingPattern(elements) {
70492         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70493         node.elements = createNodeArray(elements);
70494         return node;
70495     }
70496     ts.createObjectBindingPattern = createObjectBindingPattern;
70497     function updateObjectBindingPattern(node, elements) {
70498         return node.elements !== elements
70499             ? updateNode(createObjectBindingPattern(elements), node)
70500             : node;
70501     }
70502     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70503     function createArrayBindingPattern(elements) {
70504         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70505         node.elements = createNodeArray(elements);
70506         return node;
70507     }
70508     ts.createArrayBindingPattern = createArrayBindingPattern;
70509     function updateArrayBindingPattern(node, elements) {
70510         return node.elements !== elements
70511             ? updateNode(createArrayBindingPattern(elements), node)
70512             : node;
70513     }
70514     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70515     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70516         var node = createSynthesizedNode(191 /* BindingElement */);
70517         node.dotDotDotToken = dotDotDotToken;
70518         node.propertyName = asName(propertyName);
70519         node.name = asName(name);
70520         node.initializer = initializer;
70521         return node;
70522     }
70523     ts.createBindingElement = createBindingElement;
70524     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70525         return node.propertyName !== propertyName
70526             || node.dotDotDotToken !== dotDotDotToken
70527             || node.name !== name
70528             || node.initializer !== initializer
70529             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70530             : node;
70531     }
70532     ts.updateBindingElement = updateBindingElement;
70533     // Expression
70534     function createArrayLiteral(elements, multiLine) {
70535         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70536         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70537         if (multiLine)
70538             node.multiLine = true;
70539         return node;
70540     }
70541     ts.createArrayLiteral = createArrayLiteral;
70542     function updateArrayLiteral(node, elements) {
70543         return node.elements !== elements
70544             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70545             : node;
70546     }
70547     ts.updateArrayLiteral = updateArrayLiteral;
70548     function createObjectLiteral(properties, multiLine) {
70549         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70550         node.properties = createNodeArray(properties);
70551         if (multiLine)
70552             node.multiLine = true;
70553         return node;
70554     }
70555     ts.createObjectLiteral = createObjectLiteral;
70556     function updateObjectLiteral(node, properties) {
70557         return node.properties !== properties
70558             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70559             : node;
70560     }
70561     ts.updateObjectLiteral = updateObjectLiteral;
70562     function createPropertyAccess(expression, name) {
70563         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70564         node.expression = ts.parenthesizeForAccess(expression);
70565         node.name = asName(name);
70566         setEmitFlags(node, 131072 /* NoIndentation */);
70567         return node;
70568     }
70569     ts.createPropertyAccess = createPropertyAccess;
70570     function updatePropertyAccess(node, expression, name) {
70571         if (ts.isPropertyAccessChain(node)) {
70572             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70573         }
70574         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70575         // instead of using the default from createPropertyAccess
70576         return node.expression !== expression
70577             || node.name !== name
70578             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70579             : node;
70580     }
70581     ts.updatePropertyAccess = updatePropertyAccess;
70582     function createPropertyAccessChain(expression, questionDotToken, name) {
70583         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70584         node.flags |= 32 /* OptionalChain */;
70585         node.expression = ts.parenthesizeForAccess(expression);
70586         node.questionDotToken = questionDotToken;
70587         node.name = asName(name);
70588         setEmitFlags(node, 131072 /* NoIndentation */);
70589         return node;
70590     }
70591     ts.createPropertyAccessChain = createPropertyAccessChain;
70592     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70593         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70594         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70595         // instead of using the default from createPropertyAccess
70596         return node.expression !== expression
70597             || node.questionDotToken !== questionDotToken
70598             || node.name !== name
70599             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70600             : node;
70601     }
70602     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70603     function createElementAccess(expression, index) {
70604         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70605         node.expression = ts.parenthesizeForAccess(expression);
70606         node.argumentExpression = asExpression(index);
70607         return node;
70608     }
70609     ts.createElementAccess = createElementAccess;
70610     function updateElementAccess(node, expression, argumentExpression) {
70611         if (ts.isOptionalChain(node)) {
70612             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70613         }
70614         return node.expression !== expression
70615             || node.argumentExpression !== argumentExpression
70616             ? updateNode(createElementAccess(expression, argumentExpression), node)
70617             : node;
70618     }
70619     ts.updateElementAccess = updateElementAccess;
70620     function createElementAccessChain(expression, questionDotToken, index) {
70621         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70622         node.flags |= 32 /* OptionalChain */;
70623         node.expression = ts.parenthesizeForAccess(expression);
70624         node.questionDotToken = questionDotToken;
70625         node.argumentExpression = asExpression(index);
70626         return node;
70627     }
70628     ts.createElementAccessChain = createElementAccessChain;
70629     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70630         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70631         return node.expression !== expression
70632             || node.questionDotToken !== questionDotToken
70633             || node.argumentExpression !== argumentExpression
70634             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70635             : node;
70636     }
70637     ts.updateElementAccessChain = updateElementAccessChain;
70638     function createCall(expression, typeArguments, argumentsArray) {
70639         var node = createSynthesizedNode(196 /* CallExpression */);
70640         node.expression = ts.parenthesizeForAccess(expression);
70641         node.typeArguments = asNodeArray(typeArguments);
70642         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70643         return node;
70644     }
70645     ts.createCall = createCall;
70646     function updateCall(node, expression, typeArguments, argumentsArray) {
70647         if (ts.isOptionalChain(node)) {
70648             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70649         }
70650         return node.expression !== expression
70651             || node.typeArguments !== typeArguments
70652             || node.arguments !== argumentsArray
70653             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70654             : node;
70655     }
70656     ts.updateCall = updateCall;
70657     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70658         var node = createSynthesizedNode(196 /* CallExpression */);
70659         node.flags |= 32 /* OptionalChain */;
70660         node.expression = ts.parenthesizeForAccess(expression);
70661         node.questionDotToken = questionDotToken;
70662         node.typeArguments = asNodeArray(typeArguments);
70663         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70664         return node;
70665     }
70666     ts.createCallChain = createCallChain;
70667     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70668         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70669         return node.expression !== expression
70670             || node.questionDotToken !== questionDotToken
70671             || node.typeArguments !== typeArguments
70672             || node.arguments !== argumentsArray
70673             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70674             : node;
70675     }
70676     ts.updateCallChain = updateCallChain;
70677     function createNew(expression, typeArguments, argumentsArray) {
70678         var node = createSynthesizedNode(197 /* NewExpression */);
70679         node.expression = ts.parenthesizeForNew(expression);
70680         node.typeArguments = asNodeArray(typeArguments);
70681         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70682         return node;
70683     }
70684     ts.createNew = createNew;
70685     function updateNew(node, expression, typeArguments, argumentsArray) {
70686         return node.expression !== expression
70687             || node.typeArguments !== typeArguments
70688             || node.arguments !== argumentsArray
70689             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70690             : node;
70691     }
70692     ts.updateNew = updateNew;
70693     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70694         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70695         node.tag = ts.parenthesizeForAccess(tag);
70696         if (template) {
70697             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70698             node.template = template;
70699         }
70700         else {
70701             node.typeArguments = undefined;
70702             node.template = typeArgumentsOrTemplate;
70703         }
70704         return node;
70705     }
70706     ts.createTaggedTemplate = createTaggedTemplate;
70707     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70708         return node.tag !== tag
70709             || (template
70710                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70711                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70712             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70713             : node;
70714     }
70715     ts.updateTaggedTemplate = updateTaggedTemplate;
70716     function createTypeAssertion(type, expression) {
70717         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70718         node.type = type;
70719         node.expression = ts.parenthesizePrefixOperand(expression);
70720         return node;
70721     }
70722     ts.createTypeAssertion = createTypeAssertion;
70723     function updateTypeAssertion(node, type, expression) {
70724         return node.type !== type
70725             || node.expression !== expression
70726             ? updateNode(createTypeAssertion(type, expression), node)
70727             : node;
70728     }
70729     ts.updateTypeAssertion = updateTypeAssertion;
70730     function createParen(expression) {
70731         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70732         node.expression = expression;
70733         return node;
70734     }
70735     ts.createParen = createParen;
70736     function updateParen(node, expression) {
70737         return node.expression !== expression
70738             ? updateNode(createParen(expression), node)
70739             : node;
70740     }
70741     ts.updateParen = updateParen;
70742     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70743         var node = createSynthesizedNode(201 /* FunctionExpression */);
70744         node.modifiers = asNodeArray(modifiers);
70745         node.asteriskToken = asteriskToken;
70746         node.name = asName(name);
70747         node.typeParameters = asNodeArray(typeParameters);
70748         node.parameters = createNodeArray(parameters);
70749         node.type = type;
70750         node.body = body;
70751         return node;
70752     }
70753     ts.createFunctionExpression = createFunctionExpression;
70754     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70755         return node.name !== name
70756             || node.modifiers !== modifiers
70757             || node.asteriskToken !== asteriskToken
70758             || node.typeParameters !== typeParameters
70759             || node.parameters !== parameters
70760             || node.type !== type
70761             || node.body !== body
70762             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70763             : node;
70764     }
70765     ts.updateFunctionExpression = updateFunctionExpression;
70766     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70767         var node = createSynthesizedNode(202 /* ArrowFunction */);
70768         node.modifiers = asNodeArray(modifiers);
70769         node.typeParameters = asNodeArray(typeParameters);
70770         node.parameters = createNodeArray(parameters);
70771         node.type = type;
70772         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70773         node.body = ts.parenthesizeConciseBody(body);
70774         return node;
70775     }
70776     ts.createArrowFunction = createArrowFunction;
70777     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70778         return node.modifiers !== modifiers
70779             || node.typeParameters !== typeParameters
70780             || node.parameters !== parameters
70781             || node.type !== type
70782             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70783             || node.body !== body
70784             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70785             : node;
70786     }
70787     ts.updateArrowFunction = updateArrowFunction;
70788     function createDelete(expression) {
70789         var node = createSynthesizedNode(203 /* DeleteExpression */);
70790         node.expression = ts.parenthesizePrefixOperand(expression);
70791         return node;
70792     }
70793     ts.createDelete = createDelete;
70794     function updateDelete(node, expression) {
70795         return node.expression !== expression
70796             ? updateNode(createDelete(expression), node)
70797             : node;
70798     }
70799     ts.updateDelete = updateDelete;
70800     function createTypeOf(expression) {
70801         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70802         node.expression = ts.parenthesizePrefixOperand(expression);
70803         return node;
70804     }
70805     ts.createTypeOf = createTypeOf;
70806     function updateTypeOf(node, expression) {
70807         return node.expression !== expression
70808             ? updateNode(createTypeOf(expression), node)
70809             : node;
70810     }
70811     ts.updateTypeOf = updateTypeOf;
70812     function createVoid(expression) {
70813         var node = createSynthesizedNode(205 /* VoidExpression */);
70814         node.expression = ts.parenthesizePrefixOperand(expression);
70815         return node;
70816     }
70817     ts.createVoid = createVoid;
70818     function updateVoid(node, expression) {
70819         return node.expression !== expression
70820             ? updateNode(createVoid(expression), node)
70821             : node;
70822     }
70823     ts.updateVoid = updateVoid;
70824     function createAwait(expression) {
70825         var node = createSynthesizedNode(206 /* AwaitExpression */);
70826         node.expression = ts.parenthesizePrefixOperand(expression);
70827         return node;
70828     }
70829     ts.createAwait = createAwait;
70830     function updateAwait(node, expression) {
70831         return node.expression !== expression
70832             ? updateNode(createAwait(expression), node)
70833             : node;
70834     }
70835     ts.updateAwait = updateAwait;
70836     function createPrefix(operator, operand) {
70837         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
70838         node.operator = operator;
70839         node.operand = ts.parenthesizePrefixOperand(operand);
70840         return node;
70841     }
70842     ts.createPrefix = createPrefix;
70843     function updatePrefix(node, operand) {
70844         return node.operand !== operand
70845             ? updateNode(createPrefix(node.operator, operand), node)
70846             : node;
70847     }
70848     ts.updatePrefix = updatePrefix;
70849     function createPostfix(operand, operator) {
70850         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
70851         node.operand = ts.parenthesizePostfixOperand(operand);
70852         node.operator = operator;
70853         return node;
70854     }
70855     ts.createPostfix = createPostfix;
70856     function updatePostfix(node, operand) {
70857         return node.operand !== operand
70858             ? updateNode(createPostfix(operand, node.operator), node)
70859             : node;
70860     }
70861     ts.updatePostfix = updatePostfix;
70862     function createBinary(left, operator, right) {
70863         var node = createSynthesizedNode(209 /* BinaryExpression */);
70864         var operatorToken = asToken(operator);
70865         var operatorKind = operatorToken.kind;
70866         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
70867         node.operatorToken = operatorToken;
70868         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
70869         return node;
70870     }
70871     ts.createBinary = createBinary;
70872     function updateBinary(node, left, right, operator) {
70873         return node.left !== left
70874             || node.right !== right
70875             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
70876             : node;
70877     }
70878     ts.updateBinary = updateBinary;
70879     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
70880         var node = createSynthesizedNode(210 /* ConditionalExpression */);
70881         node.condition = ts.parenthesizeForConditionalHead(condition);
70882         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
70883         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
70884         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
70885         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
70886         return node;
70887     }
70888     ts.createConditional = createConditional;
70889     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
70890         return node.condition !== condition
70891             || node.questionToken !== questionToken
70892             || node.whenTrue !== whenTrue
70893             || node.colonToken !== colonToken
70894             || node.whenFalse !== whenFalse
70895             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
70896             : node;
70897     }
70898     ts.updateConditional = updateConditional;
70899     function createTemplateExpression(head, templateSpans) {
70900         var node = createSynthesizedNode(211 /* TemplateExpression */);
70901         node.head = head;
70902         node.templateSpans = createNodeArray(templateSpans);
70903         return node;
70904     }
70905     ts.createTemplateExpression = createTemplateExpression;
70906     function updateTemplateExpression(node, head, templateSpans) {
70907         return node.head !== head
70908             || node.templateSpans !== templateSpans
70909             ? updateNode(createTemplateExpression(head, templateSpans), node)
70910             : node;
70911     }
70912     ts.updateTemplateExpression = updateTemplateExpression;
70913     var rawTextScanner;
70914     var invalidValueSentinel = {};
70915     function getCookedText(kind, rawText) {
70916         if (!rawTextScanner) {
70917             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
70918         }
70919         switch (kind) {
70920             case 14 /* NoSubstitutionTemplateLiteral */:
70921                 rawTextScanner.setText("`" + rawText + "`");
70922                 break;
70923             case 15 /* TemplateHead */:
70924                 rawTextScanner.setText("`" + rawText + "${");
70925                 break;
70926             case 16 /* TemplateMiddle */:
70927                 rawTextScanner.setText("}" + rawText + "${");
70928                 break;
70929             case 17 /* TemplateTail */:
70930                 rawTextScanner.setText("}" + rawText + "`");
70931                 break;
70932         }
70933         var token = rawTextScanner.scan();
70934         if (token === 23 /* CloseBracketToken */) {
70935             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
70936         }
70937         if (rawTextScanner.isUnterminated()) {
70938             rawTextScanner.setText(undefined);
70939             return invalidValueSentinel;
70940         }
70941         var tokenValue;
70942         switch (token) {
70943             case 14 /* NoSubstitutionTemplateLiteral */:
70944             case 15 /* TemplateHead */:
70945             case 16 /* TemplateMiddle */:
70946             case 17 /* TemplateTail */:
70947                 tokenValue = rawTextScanner.getTokenValue();
70948                 break;
70949         }
70950         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
70951             rawTextScanner.setText(undefined);
70952             return invalidValueSentinel;
70953         }
70954         rawTextScanner.setText(undefined);
70955         return tokenValue;
70956     }
70957     function createTemplateLiteralLikeNode(kind, text, rawText) {
70958         var node = createSynthesizedNode(kind);
70959         node.text = text;
70960         if (rawText === undefined || text === rawText) {
70961             node.rawText = rawText;
70962         }
70963         else {
70964             var cooked = getCookedText(kind, rawText);
70965             if (typeof cooked === "object") {
70966                 return ts.Debug.fail("Invalid raw text");
70967             }
70968             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
70969             node.rawText = rawText;
70970         }
70971         return node;
70972     }
70973     function createTemplateHead(text, rawText) {
70974         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
70975         node.text = text;
70976         return node;
70977     }
70978     ts.createTemplateHead = createTemplateHead;
70979     function createTemplateMiddle(text, rawText) {
70980         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
70981         node.text = text;
70982         return node;
70983     }
70984     ts.createTemplateMiddle = createTemplateMiddle;
70985     function createTemplateTail(text, rawText) {
70986         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
70987         node.text = text;
70988         return node;
70989     }
70990     ts.createTemplateTail = createTemplateTail;
70991     function createNoSubstitutionTemplateLiteral(text, rawText) {
70992         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
70993         return node;
70994     }
70995     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
70996     function createYield(asteriskTokenOrExpression, expression) {
70997         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
70998         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
70999         var node = createSynthesizedNode(212 /* YieldExpression */);
71000         node.asteriskToken = asteriskToken;
71001         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71002         return node;
71003     }
71004     ts.createYield = createYield;
71005     function updateYield(node, asteriskToken, expression) {
71006         return node.expression !== expression
71007             || node.asteriskToken !== asteriskToken
71008             ? updateNode(createYield(asteriskToken, expression), node)
71009             : node;
71010     }
71011     ts.updateYield = updateYield;
71012     function createSpread(expression) {
71013         var node = createSynthesizedNode(213 /* SpreadElement */);
71014         node.expression = ts.parenthesizeExpressionForList(expression);
71015         return node;
71016     }
71017     ts.createSpread = createSpread;
71018     function updateSpread(node, expression) {
71019         return node.expression !== expression
71020             ? updateNode(createSpread(expression), node)
71021             : node;
71022     }
71023     ts.updateSpread = updateSpread;
71024     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71025         var node = createSynthesizedNode(214 /* ClassExpression */);
71026         node.decorators = undefined;
71027         node.modifiers = asNodeArray(modifiers);
71028         node.name = asName(name);
71029         node.typeParameters = asNodeArray(typeParameters);
71030         node.heritageClauses = asNodeArray(heritageClauses);
71031         node.members = createNodeArray(members);
71032         return node;
71033     }
71034     ts.createClassExpression = createClassExpression;
71035     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71036         return node.modifiers !== modifiers
71037             || node.name !== name
71038             || node.typeParameters !== typeParameters
71039             || node.heritageClauses !== heritageClauses
71040             || node.members !== members
71041             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71042             : node;
71043     }
71044     ts.updateClassExpression = updateClassExpression;
71045     function createOmittedExpression() {
71046         return createSynthesizedNode(215 /* OmittedExpression */);
71047     }
71048     ts.createOmittedExpression = createOmittedExpression;
71049     function createExpressionWithTypeArguments(typeArguments, expression) {
71050         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71051         node.expression = ts.parenthesizeForAccess(expression);
71052         node.typeArguments = asNodeArray(typeArguments);
71053         return node;
71054     }
71055     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71056     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71057         return node.typeArguments !== typeArguments
71058             || node.expression !== expression
71059             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71060             : node;
71061     }
71062     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71063     function createAsExpression(expression, type) {
71064         var node = createSynthesizedNode(217 /* AsExpression */);
71065         node.expression = expression;
71066         node.type = type;
71067         return node;
71068     }
71069     ts.createAsExpression = createAsExpression;
71070     function updateAsExpression(node, expression, type) {
71071         return node.expression !== expression
71072             || node.type !== type
71073             ? updateNode(createAsExpression(expression, type), node)
71074             : node;
71075     }
71076     ts.updateAsExpression = updateAsExpression;
71077     function createNonNullExpression(expression) {
71078         var node = createSynthesizedNode(218 /* NonNullExpression */);
71079         node.expression = ts.parenthesizeForAccess(expression);
71080         return node;
71081     }
71082     ts.createNonNullExpression = createNonNullExpression;
71083     function updateNonNullExpression(node, expression) {
71084         if (ts.isNonNullChain(node)) {
71085             return updateNonNullChain(node, expression);
71086         }
71087         return node.expression !== expression
71088             ? updateNode(createNonNullExpression(expression), node)
71089             : node;
71090     }
71091     ts.updateNonNullExpression = updateNonNullExpression;
71092     function createNonNullChain(expression) {
71093         var node = createSynthesizedNode(218 /* NonNullExpression */);
71094         node.flags |= 32 /* OptionalChain */;
71095         node.expression = ts.parenthesizeForAccess(expression);
71096         return node;
71097     }
71098     ts.createNonNullChain = createNonNullChain;
71099     function updateNonNullChain(node, expression) {
71100         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71101         return node.expression !== expression
71102             ? updateNode(createNonNullChain(expression), node)
71103             : node;
71104     }
71105     ts.updateNonNullChain = updateNonNullChain;
71106     function createMetaProperty(keywordToken, name) {
71107         var node = createSynthesizedNode(219 /* MetaProperty */);
71108         node.keywordToken = keywordToken;
71109         node.name = name;
71110         return node;
71111     }
71112     ts.createMetaProperty = createMetaProperty;
71113     function updateMetaProperty(node, name) {
71114         return node.name !== name
71115             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71116             : node;
71117     }
71118     ts.updateMetaProperty = updateMetaProperty;
71119     // Misc
71120     function createTemplateSpan(expression, literal) {
71121         var node = createSynthesizedNode(221 /* TemplateSpan */);
71122         node.expression = expression;
71123         node.literal = literal;
71124         return node;
71125     }
71126     ts.createTemplateSpan = createTemplateSpan;
71127     function updateTemplateSpan(node, expression, literal) {
71128         return node.expression !== expression
71129             || node.literal !== literal
71130             ? updateNode(createTemplateSpan(expression, literal), node)
71131             : node;
71132     }
71133     ts.updateTemplateSpan = updateTemplateSpan;
71134     function createSemicolonClassElement() {
71135         return createSynthesizedNode(222 /* SemicolonClassElement */);
71136     }
71137     ts.createSemicolonClassElement = createSemicolonClassElement;
71138     // Element
71139     function createBlock(statements, multiLine) {
71140         var block = createSynthesizedNode(223 /* Block */);
71141         block.statements = createNodeArray(statements);
71142         if (multiLine)
71143             block.multiLine = multiLine;
71144         return block;
71145     }
71146     ts.createBlock = createBlock;
71147     function updateBlock(node, statements) {
71148         return node.statements !== statements
71149             ? updateNode(createBlock(statements, node.multiLine), node)
71150             : node;
71151     }
71152     ts.updateBlock = updateBlock;
71153     function createVariableStatement(modifiers, declarationList) {
71154         var node = createSynthesizedNode(225 /* VariableStatement */);
71155         node.decorators = undefined;
71156         node.modifiers = asNodeArray(modifiers);
71157         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71158         return node;
71159     }
71160     ts.createVariableStatement = createVariableStatement;
71161     function updateVariableStatement(node, modifiers, declarationList) {
71162         return node.modifiers !== modifiers
71163             || node.declarationList !== declarationList
71164             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71165             : node;
71166     }
71167     ts.updateVariableStatement = updateVariableStatement;
71168     function createEmptyStatement() {
71169         return createSynthesizedNode(224 /* EmptyStatement */);
71170     }
71171     ts.createEmptyStatement = createEmptyStatement;
71172     function createExpressionStatement(expression) {
71173         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71174         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71175         return node;
71176     }
71177     ts.createExpressionStatement = createExpressionStatement;
71178     function updateExpressionStatement(node, expression) {
71179         return node.expression !== expression
71180             ? updateNode(createExpressionStatement(expression), node)
71181             : node;
71182     }
71183     ts.updateExpressionStatement = updateExpressionStatement;
71184     /** @deprecated Use `createExpressionStatement` instead.  */
71185     ts.createStatement = createExpressionStatement;
71186     /** @deprecated Use `updateExpressionStatement` instead.  */
71187     ts.updateStatement = updateExpressionStatement;
71188     function createIf(expression, thenStatement, elseStatement) {
71189         var node = createSynthesizedNode(227 /* IfStatement */);
71190         node.expression = expression;
71191         node.thenStatement = asEmbeddedStatement(thenStatement);
71192         node.elseStatement = asEmbeddedStatement(elseStatement);
71193         return node;
71194     }
71195     ts.createIf = createIf;
71196     function updateIf(node, expression, thenStatement, elseStatement) {
71197         return node.expression !== expression
71198             || node.thenStatement !== thenStatement
71199             || node.elseStatement !== elseStatement
71200             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71201             : node;
71202     }
71203     ts.updateIf = updateIf;
71204     function createDo(statement, expression) {
71205         var node = createSynthesizedNode(228 /* DoStatement */);
71206         node.statement = asEmbeddedStatement(statement);
71207         node.expression = expression;
71208         return node;
71209     }
71210     ts.createDo = createDo;
71211     function updateDo(node, statement, expression) {
71212         return node.statement !== statement
71213             || node.expression !== expression
71214             ? updateNode(createDo(statement, expression), node)
71215             : node;
71216     }
71217     ts.updateDo = updateDo;
71218     function createWhile(expression, statement) {
71219         var node = createSynthesizedNode(229 /* WhileStatement */);
71220         node.expression = expression;
71221         node.statement = asEmbeddedStatement(statement);
71222         return node;
71223     }
71224     ts.createWhile = createWhile;
71225     function updateWhile(node, expression, statement) {
71226         return node.expression !== expression
71227             || node.statement !== statement
71228             ? updateNode(createWhile(expression, statement), node)
71229             : node;
71230     }
71231     ts.updateWhile = updateWhile;
71232     function createFor(initializer, condition, incrementor, statement) {
71233         var node = createSynthesizedNode(230 /* ForStatement */);
71234         node.initializer = initializer;
71235         node.condition = condition;
71236         node.incrementor = incrementor;
71237         node.statement = asEmbeddedStatement(statement);
71238         return node;
71239     }
71240     ts.createFor = createFor;
71241     function updateFor(node, initializer, condition, incrementor, statement) {
71242         return node.initializer !== initializer
71243             || node.condition !== condition
71244             || node.incrementor !== incrementor
71245             || node.statement !== statement
71246             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71247             : node;
71248     }
71249     ts.updateFor = updateFor;
71250     function createForIn(initializer, expression, statement) {
71251         var node = createSynthesizedNode(231 /* ForInStatement */);
71252         node.initializer = initializer;
71253         node.expression = expression;
71254         node.statement = asEmbeddedStatement(statement);
71255         return node;
71256     }
71257     ts.createForIn = createForIn;
71258     function updateForIn(node, initializer, expression, statement) {
71259         return node.initializer !== initializer
71260             || node.expression !== expression
71261             || node.statement !== statement
71262             ? updateNode(createForIn(initializer, expression, statement), node)
71263             : node;
71264     }
71265     ts.updateForIn = updateForIn;
71266     function createForOf(awaitModifier, initializer, expression, statement) {
71267         var node = createSynthesizedNode(232 /* ForOfStatement */);
71268         node.awaitModifier = awaitModifier;
71269         node.initializer = initializer;
71270         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71271         node.statement = asEmbeddedStatement(statement);
71272         return node;
71273     }
71274     ts.createForOf = createForOf;
71275     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71276         return node.awaitModifier !== awaitModifier
71277             || node.initializer !== initializer
71278             || node.expression !== expression
71279             || node.statement !== statement
71280             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71281             : node;
71282     }
71283     ts.updateForOf = updateForOf;
71284     function createContinue(label) {
71285         var node = createSynthesizedNode(233 /* ContinueStatement */);
71286         node.label = asName(label);
71287         return node;
71288     }
71289     ts.createContinue = createContinue;
71290     function updateContinue(node, label) {
71291         return node.label !== label
71292             ? updateNode(createContinue(label), node)
71293             : node;
71294     }
71295     ts.updateContinue = updateContinue;
71296     function createBreak(label) {
71297         var node = createSynthesizedNode(234 /* BreakStatement */);
71298         node.label = asName(label);
71299         return node;
71300     }
71301     ts.createBreak = createBreak;
71302     function updateBreak(node, label) {
71303         return node.label !== label
71304             ? updateNode(createBreak(label), node)
71305             : node;
71306     }
71307     ts.updateBreak = updateBreak;
71308     function createReturn(expression) {
71309         var node = createSynthesizedNode(235 /* ReturnStatement */);
71310         node.expression = expression;
71311         return node;
71312     }
71313     ts.createReturn = createReturn;
71314     function updateReturn(node, expression) {
71315         return node.expression !== expression
71316             ? updateNode(createReturn(expression), node)
71317             : node;
71318     }
71319     ts.updateReturn = updateReturn;
71320     function createWith(expression, statement) {
71321         var node = createSynthesizedNode(236 /* WithStatement */);
71322         node.expression = expression;
71323         node.statement = asEmbeddedStatement(statement);
71324         return node;
71325     }
71326     ts.createWith = createWith;
71327     function updateWith(node, expression, statement) {
71328         return node.expression !== expression
71329             || node.statement !== statement
71330             ? updateNode(createWith(expression, statement), node)
71331             : node;
71332     }
71333     ts.updateWith = updateWith;
71334     function createSwitch(expression, caseBlock) {
71335         var node = createSynthesizedNode(237 /* SwitchStatement */);
71336         node.expression = ts.parenthesizeExpressionForList(expression);
71337         node.caseBlock = caseBlock;
71338         return node;
71339     }
71340     ts.createSwitch = createSwitch;
71341     function updateSwitch(node, expression, caseBlock) {
71342         return node.expression !== expression
71343             || node.caseBlock !== caseBlock
71344             ? updateNode(createSwitch(expression, caseBlock), node)
71345             : node;
71346     }
71347     ts.updateSwitch = updateSwitch;
71348     function createLabel(label, statement) {
71349         var node = createSynthesizedNode(238 /* LabeledStatement */);
71350         node.label = asName(label);
71351         node.statement = asEmbeddedStatement(statement);
71352         return node;
71353     }
71354     ts.createLabel = createLabel;
71355     function updateLabel(node, label, statement) {
71356         return node.label !== label
71357             || node.statement !== statement
71358             ? updateNode(createLabel(label, statement), node)
71359             : node;
71360     }
71361     ts.updateLabel = updateLabel;
71362     function createThrow(expression) {
71363         var node = createSynthesizedNode(239 /* ThrowStatement */);
71364         node.expression = expression;
71365         return node;
71366     }
71367     ts.createThrow = createThrow;
71368     function updateThrow(node, expression) {
71369         return node.expression !== expression
71370             ? updateNode(createThrow(expression), node)
71371             : node;
71372     }
71373     ts.updateThrow = updateThrow;
71374     function createTry(tryBlock, catchClause, finallyBlock) {
71375         var node = createSynthesizedNode(240 /* TryStatement */);
71376         node.tryBlock = tryBlock;
71377         node.catchClause = catchClause;
71378         node.finallyBlock = finallyBlock;
71379         return node;
71380     }
71381     ts.createTry = createTry;
71382     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71383         return node.tryBlock !== tryBlock
71384             || node.catchClause !== catchClause
71385             || node.finallyBlock !== finallyBlock
71386             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71387             : node;
71388     }
71389     ts.updateTry = updateTry;
71390     function createDebuggerStatement() {
71391         return createSynthesizedNode(241 /* DebuggerStatement */);
71392     }
71393     ts.createDebuggerStatement = createDebuggerStatement;
71394     function createVariableDeclaration(name, type, initializer) {
71395         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71396         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71397         node.name = asName(name);
71398         node.type = type;
71399         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71400         return node;
71401     }
71402     ts.createVariableDeclaration = createVariableDeclaration;
71403     function updateVariableDeclaration(node, name, type, initializer) {
71404         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71405         return node.name !== name
71406             || node.type !== type
71407             || node.initializer !== initializer
71408             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71409             : node;
71410     }
71411     ts.updateVariableDeclaration = updateVariableDeclaration;
71412     /* @internal */
71413     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71414         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71415         node.name = asName(name);
71416         node.type = type;
71417         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71418         node.exclamationToken = exclaimationToken;
71419         return node;
71420     }
71421     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71422     /* @internal */
71423     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71424         return node.name !== name
71425             || node.type !== type
71426             || node.initializer !== initializer
71427             || node.exclamationToken !== exclaimationToken
71428             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71429             : node;
71430     }
71431     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71432     function createVariableDeclarationList(declarations, flags) {
71433         if (flags === void 0) { flags = 0 /* None */; }
71434         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71435         node.flags |= flags & 3 /* BlockScoped */;
71436         node.declarations = createNodeArray(declarations);
71437         return node;
71438     }
71439     ts.createVariableDeclarationList = createVariableDeclarationList;
71440     function updateVariableDeclarationList(node, declarations) {
71441         return node.declarations !== declarations
71442             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71443             : node;
71444     }
71445     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71446     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71447         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71448         node.decorators = asNodeArray(decorators);
71449         node.modifiers = asNodeArray(modifiers);
71450         node.asteriskToken = asteriskToken;
71451         node.name = asName(name);
71452         node.typeParameters = asNodeArray(typeParameters);
71453         node.parameters = createNodeArray(parameters);
71454         node.type = type;
71455         node.body = body;
71456         return node;
71457     }
71458     ts.createFunctionDeclaration = createFunctionDeclaration;
71459     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71460         return node.decorators !== decorators
71461             || node.modifiers !== modifiers
71462             || node.asteriskToken !== asteriskToken
71463             || node.name !== name
71464             || node.typeParameters !== typeParameters
71465             || node.parameters !== parameters
71466             || node.type !== type
71467             || node.body !== body
71468             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71469             : node;
71470     }
71471     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71472     /* @internal */
71473     function updateFunctionLikeBody(declaration, body) {
71474         switch (declaration.kind) {
71475             case 244 /* FunctionDeclaration */:
71476                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71477             case 161 /* MethodDeclaration */:
71478                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71479             case 163 /* GetAccessor */:
71480                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71481             case 164 /* SetAccessor */:
71482                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71483             case 162 /* Constructor */:
71484                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71485             case 201 /* FunctionExpression */:
71486                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71487             case 202 /* ArrowFunction */:
71488                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71489         }
71490     }
71491     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71492     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71493         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71494         node.decorators = asNodeArray(decorators);
71495         node.modifiers = asNodeArray(modifiers);
71496         node.name = asName(name);
71497         node.typeParameters = asNodeArray(typeParameters);
71498         node.heritageClauses = asNodeArray(heritageClauses);
71499         node.members = createNodeArray(members);
71500         return node;
71501     }
71502     ts.createClassDeclaration = createClassDeclaration;
71503     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71504         return node.decorators !== decorators
71505             || node.modifiers !== modifiers
71506             || node.name !== name
71507             || node.typeParameters !== typeParameters
71508             || node.heritageClauses !== heritageClauses
71509             || node.members !== members
71510             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71511             : node;
71512     }
71513     ts.updateClassDeclaration = updateClassDeclaration;
71514     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71515         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71516         node.decorators = asNodeArray(decorators);
71517         node.modifiers = asNodeArray(modifiers);
71518         node.name = asName(name);
71519         node.typeParameters = asNodeArray(typeParameters);
71520         node.heritageClauses = asNodeArray(heritageClauses);
71521         node.members = createNodeArray(members);
71522         return node;
71523     }
71524     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71525     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71526         return node.decorators !== decorators
71527             || node.modifiers !== modifiers
71528             || node.name !== name
71529             || node.typeParameters !== typeParameters
71530             || node.heritageClauses !== heritageClauses
71531             || node.members !== members
71532             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71533             : node;
71534     }
71535     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71536     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71537         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71538         node.decorators = asNodeArray(decorators);
71539         node.modifiers = asNodeArray(modifiers);
71540         node.name = asName(name);
71541         node.typeParameters = asNodeArray(typeParameters);
71542         node.type = type;
71543         return node;
71544     }
71545     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71546     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71547         return node.decorators !== decorators
71548             || node.modifiers !== modifiers
71549             || node.name !== name
71550             || node.typeParameters !== typeParameters
71551             || node.type !== type
71552             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71553             : node;
71554     }
71555     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71556     function createEnumDeclaration(decorators, modifiers, name, members) {
71557         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71558         node.decorators = asNodeArray(decorators);
71559         node.modifiers = asNodeArray(modifiers);
71560         node.name = asName(name);
71561         node.members = createNodeArray(members);
71562         return node;
71563     }
71564     ts.createEnumDeclaration = createEnumDeclaration;
71565     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71566         return node.decorators !== decorators
71567             || node.modifiers !== modifiers
71568             || node.name !== name
71569             || node.members !== members
71570             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71571             : node;
71572     }
71573     ts.updateEnumDeclaration = updateEnumDeclaration;
71574     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71575         if (flags === void 0) { flags = 0 /* None */; }
71576         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71577         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71578         node.decorators = asNodeArray(decorators);
71579         node.modifiers = asNodeArray(modifiers);
71580         node.name = name;
71581         node.body = body;
71582         return node;
71583     }
71584     ts.createModuleDeclaration = createModuleDeclaration;
71585     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71586         return node.decorators !== decorators
71587             || node.modifiers !== modifiers
71588             || node.name !== name
71589             || node.body !== body
71590             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71591             : node;
71592     }
71593     ts.updateModuleDeclaration = updateModuleDeclaration;
71594     function createModuleBlock(statements) {
71595         var node = createSynthesizedNode(250 /* ModuleBlock */);
71596         node.statements = createNodeArray(statements);
71597         return node;
71598     }
71599     ts.createModuleBlock = createModuleBlock;
71600     function updateModuleBlock(node, statements) {
71601         return node.statements !== statements
71602             ? updateNode(createModuleBlock(statements), node)
71603             : node;
71604     }
71605     ts.updateModuleBlock = updateModuleBlock;
71606     function createCaseBlock(clauses) {
71607         var node = createSynthesizedNode(251 /* CaseBlock */);
71608         node.clauses = createNodeArray(clauses);
71609         return node;
71610     }
71611     ts.createCaseBlock = createCaseBlock;
71612     function updateCaseBlock(node, clauses) {
71613         return node.clauses !== clauses
71614             ? updateNode(createCaseBlock(clauses), node)
71615             : node;
71616     }
71617     ts.updateCaseBlock = updateCaseBlock;
71618     function createNamespaceExportDeclaration(name) {
71619         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71620         node.name = asName(name);
71621         return node;
71622     }
71623     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71624     function updateNamespaceExportDeclaration(node, name) {
71625         return node.name !== name
71626             ? updateNode(createNamespaceExportDeclaration(name), node)
71627             : node;
71628     }
71629     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71630     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71631         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71632         node.decorators = asNodeArray(decorators);
71633         node.modifiers = asNodeArray(modifiers);
71634         node.name = asName(name);
71635         node.moduleReference = moduleReference;
71636         return node;
71637     }
71638     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71639     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71640         return node.decorators !== decorators
71641             || node.modifiers !== modifiers
71642             || node.name !== name
71643             || node.moduleReference !== moduleReference
71644             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71645             : node;
71646     }
71647     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71648     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71649         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71650         node.decorators = asNodeArray(decorators);
71651         node.modifiers = asNodeArray(modifiers);
71652         node.importClause = importClause;
71653         node.moduleSpecifier = moduleSpecifier;
71654         return node;
71655     }
71656     ts.createImportDeclaration = createImportDeclaration;
71657     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71658         return node.decorators !== decorators
71659             || node.modifiers !== modifiers
71660             || node.importClause !== importClause
71661             || node.moduleSpecifier !== moduleSpecifier
71662             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71663             : node;
71664     }
71665     ts.updateImportDeclaration = updateImportDeclaration;
71666     function createImportClause(name, namedBindings, isTypeOnly) {
71667         if (isTypeOnly === void 0) { isTypeOnly = false; }
71668         var node = createSynthesizedNode(255 /* ImportClause */);
71669         node.name = name;
71670         node.namedBindings = namedBindings;
71671         node.isTypeOnly = isTypeOnly;
71672         return node;
71673     }
71674     ts.createImportClause = createImportClause;
71675     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71676         return node.name !== name
71677             || node.namedBindings !== namedBindings
71678             || node.isTypeOnly !== isTypeOnly
71679             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71680             : node;
71681     }
71682     ts.updateImportClause = updateImportClause;
71683     function createNamespaceImport(name) {
71684         var node = createSynthesizedNode(256 /* NamespaceImport */);
71685         node.name = name;
71686         return node;
71687     }
71688     ts.createNamespaceImport = createNamespaceImport;
71689     function createNamespaceExport(name) {
71690         var node = createSynthesizedNode(262 /* NamespaceExport */);
71691         node.name = name;
71692         return node;
71693     }
71694     ts.createNamespaceExport = createNamespaceExport;
71695     function updateNamespaceImport(node, name) {
71696         return node.name !== name
71697             ? updateNode(createNamespaceImport(name), node)
71698             : node;
71699     }
71700     ts.updateNamespaceImport = updateNamespaceImport;
71701     function updateNamespaceExport(node, name) {
71702         return node.name !== name
71703             ? updateNode(createNamespaceExport(name), node)
71704             : node;
71705     }
71706     ts.updateNamespaceExport = updateNamespaceExport;
71707     function createNamedImports(elements) {
71708         var node = createSynthesizedNode(257 /* NamedImports */);
71709         node.elements = createNodeArray(elements);
71710         return node;
71711     }
71712     ts.createNamedImports = createNamedImports;
71713     function updateNamedImports(node, elements) {
71714         return node.elements !== elements
71715             ? updateNode(createNamedImports(elements), node)
71716             : node;
71717     }
71718     ts.updateNamedImports = updateNamedImports;
71719     function createImportSpecifier(propertyName, name) {
71720         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71721         node.propertyName = propertyName;
71722         node.name = name;
71723         return node;
71724     }
71725     ts.createImportSpecifier = createImportSpecifier;
71726     function updateImportSpecifier(node, propertyName, name) {
71727         return node.propertyName !== propertyName
71728             || node.name !== name
71729             ? updateNode(createImportSpecifier(propertyName, name), node)
71730             : node;
71731     }
71732     ts.updateImportSpecifier = updateImportSpecifier;
71733     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71734         var node = createSynthesizedNode(259 /* ExportAssignment */);
71735         node.decorators = asNodeArray(decorators);
71736         node.modifiers = asNodeArray(modifiers);
71737         node.isExportEquals = isExportEquals;
71738         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71739         return node;
71740     }
71741     ts.createExportAssignment = createExportAssignment;
71742     function updateExportAssignment(node, decorators, modifiers, expression) {
71743         return node.decorators !== decorators
71744             || node.modifiers !== modifiers
71745             || node.expression !== expression
71746             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71747             : node;
71748     }
71749     ts.updateExportAssignment = updateExportAssignment;
71750     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71751         if (isTypeOnly === void 0) { isTypeOnly = false; }
71752         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71753         node.decorators = asNodeArray(decorators);
71754         node.modifiers = asNodeArray(modifiers);
71755         node.isTypeOnly = isTypeOnly;
71756         node.exportClause = exportClause;
71757         node.moduleSpecifier = moduleSpecifier;
71758         return node;
71759     }
71760     ts.createExportDeclaration = createExportDeclaration;
71761     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71762         return node.decorators !== decorators
71763             || node.modifiers !== modifiers
71764             || node.isTypeOnly !== isTypeOnly
71765             || node.exportClause !== exportClause
71766             || node.moduleSpecifier !== moduleSpecifier
71767             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71768             : node;
71769     }
71770     ts.updateExportDeclaration = updateExportDeclaration;
71771     /* @internal */
71772     function createEmptyExports() {
71773         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71774     }
71775     ts.createEmptyExports = createEmptyExports;
71776     function createNamedExports(elements) {
71777         var node = createSynthesizedNode(261 /* NamedExports */);
71778         node.elements = createNodeArray(elements);
71779         return node;
71780     }
71781     ts.createNamedExports = createNamedExports;
71782     function updateNamedExports(node, elements) {
71783         return node.elements !== elements
71784             ? updateNode(createNamedExports(elements), node)
71785             : node;
71786     }
71787     ts.updateNamedExports = updateNamedExports;
71788     function createExportSpecifier(propertyName, name) {
71789         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71790         node.propertyName = asName(propertyName);
71791         node.name = asName(name);
71792         return node;
71793     }
71794     ts.createExportSpecifier = createExportSpecifier;
71795     function updateExportSpecifier(node, propertyName, name) {
71796         return node.propertyName !== propertyName
71797             || node.name !== name
71798             ? updateNode(createExportSpecifier(propertyName, name), node)
71799             : node;
71800     }
71801     ts.updateExportSpecifier = updateExportSpecifier;
71802     // Module references
71803     function createExternalModuleReference(expression) {
71804         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71805         node.expression = expression;
71806         return node;
71807     }
71808     ts.createExternalModuleReference = createExternalModuleReference;
71809     function updateExternalModuleReference(node, expression) {
71810         return node.expression !== expression
71811             ? updateNode(createExternalModuleReference(expression), node)
71812             : node;
71813     }
71814     ts.updateExternalModuleReference = updateExternalModuleReference;
71815     // JSDoc
71816     /* @internal */
71817     function createJSDocTypeExpression(type) {
71818         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
71819         node.type = type;
71820         return node;
71821     }
71822     ts.createJSDocTypeExpression = createJSDocTypeExpression;
71823     /* @internal */
71824     function createJSDocTypeTag(typeExpression, comment) {
71825         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
71826         tag.typeExpression = typeExpression;
71827         tag.comment = comment;
71828         return tag;
71829     }
71830     ts.createJSDocTypeTag = createJSDocTypeTag;
71831     /* @internal */
71832     function createJSDocReturnTag(typeExpression, comment) {
71833         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
71834         tag.typeExpression = typeExpression;
71835         tag.comment = comment;
71836         return tag;
71837     }
71838     ts.createJSDocReturnTag = createJSDocReturnTag;
71839     /** @internal */
71840     function createJSDocThisTag(typeExpression) {
71841         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
71842         tag.typeExpression = typeExpression;
71843         return tag;
71844     }
71845     ts.createJSDocThisTag = createJSDocThisTag;
71846     /* @internal */
71847     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
71848         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
71849         tag.typeExpression = typeExpression;
71850         tag.name = name;
71851         tag.isBracketed = isBracketed;
71852         tag.comment = comment;
71853         return tag;
71854     }
71855     ts.createJSDocParamTag = createJSDocParamTag;
71856     /* @internal */
71857     function createJSDocClassTag() {
71858         return createJSDocTag(310 /* JSDocClassTag */, "class");
71859     }
71860     ts.createJSDocClassTag = createJSDocClassTag;
71861     /* @internal */
71862     function createJSDocComment(comment, tags) {
71863         var node = createSynthesizedNode(303 /* JSDocComment */);
71864         node.comment = comment;
71865         node.tags = tags;
71866         return node;
71867     }
71868     ts.createJSDocComment = createJSDocComment;
71869     /* @internal */
71870     function createJSDocTag(kind, tagName) {
71871         var node = createSynthesizedNode(kind);
71872         node.tagName = createIdentifier(tagName);
71873         return node;
71874     }
71875     // JSX
71876     function createJsxElement(openingElement, children, closingElement) {
71877         var node = createSynthesizedNode(266 /* JsxElement */);
71878         node.openingElement = openingElement;
71879         node.children = createNodeArray(children);
71880         node.closingElement = closingElement;
71881         return node;
71882     }
71883     ts.createJsxElement = createJsxElement;
71884     function updateJsxElement(node, openingElement, children, closingElement) {
71885         return node.openingElement !== openingElement
71886             || node.children !== children
71887             || node.closingElement !== closingElement
71888             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
71889             : node;
71890     }
71891     ts.updateJsxElement = updateJsxElement;
71892     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
71893         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
71894         node.tagName = tagName;
71895         node.typeArguments = asNodeArray(typeArguments);
71896         node.attributes = attributes;
71897         return node;
71898     }
71899     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
71900     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
71901         return node.tagName !== tagName
71902             || node.typeArguments !== typeArguments
71903             || node.attributes !== attributes
71904             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
71905             : node;
71906     }
71907     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
71908     function createJsxOpeningElement(tagName, typeArguments, attributes) {
71909         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
71910         node.tagName = tagName;
71911         node.typeArguments = asNodeArray(typeArguments);
71912         node.attributes = attributes;
71913         return node;
71914     }
71915     ts.createJsxOpeningElement = createJsxOpeningElement;
71916     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
71917         return node.tagName !== tagName
71918             || node.typeArguments !== typeArguments
71919             || node.attributes !== attributes
71920             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
71921             : node;
71922     }
71923     ts.updateJsxOpeningElement = updateJsxOpeningElement;
71924     function createJsxClosingElement(tagName) {
71925         var node = createSynthesizedNode(269 /* JsxClosingElement */);
71926         node.tagName = tagName;
71927         return node;
71928     }
71929     ts.createJsxClosingElement = createJsxClosingElement;
71930     function updateJsxClosingElement(node, tagName) {
71931         return node.tagName !== tagName
71932             ? updateNode(createJsxClosingElement(tagName), node)
71933             : node;
71934     }
71935     ts.updateJsxClosingElement = updateJsxClosingElement;
71936     function createJsxFragment(openingFragment, children, closingFragment) {
71937         var node = createSynthesizedNode(270 /* JsxFragment */);
71938         node.openingFragment = openingFragment;
71939         node.children = createNodeArray(children);
71940         node.closingFragment = closingFragment;
71941         return node;
71942     }
71943     ts.createJsxFragment = createJsxFragment;
71944     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
71945         var node = createSynthesizedNode(11 /* JsxText */);
71946         node.text = text;
71947         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
71948         return node;
71949     }
71950     ts.createJsxText = createJsxText;
71951     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
71952         return node.text !== text
71953             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
71954             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
71955             : node;
71956     }
71957     ts.updateJsxText = updateJsxText;
71958     function createJsxOpeningFragment() {
71959         return createSynthesizedNode(271 /* JsxOpeningFragment */);
71960     }
71961     ts.createJsxOpeningFragment = createJsxOpeningFragment;
71962     function createJsxJsxClosingFragment() {
71963         return createSynthesizedNode(272 /* JsxClosingFragment */);
71964     }
71965     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
71966     function updateJsxFragment(node, openingFragment, children, closingFragment) {
71967         return node.openingFragment !== openingFragment
71968             || node.children !== children
71969             || node.closingFragment !== closingFragment
71970             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
71971             : node;
71972     }
71973     ts.updateJsxFragment = updateJsxFragment;
71974     function createJsxAttribute(name, initializer) {
71975         var node = createSynthesizedNode(273 /* JsxAttribute */);
71976         node.name = name;
71977         node.initializer = initializer;
71978         return node;
71979     }
71980     ts.createJsxAttribute = createJsxAttribute;
71981     function updateJsxAttribute(node, name, initializer) {
71982         return node.name !== name
71983             || node.initializer !== initializer
71984             ? updateNode(createJsxAttribute(name, initializer), node)
71985             : node;
71986     }
71987     ts.updateJsxAttribute = updateJsxAttribute;
71988     function createJsxAttributes(properties) {
71989         var node = createSynthesizedNode(274 /* JsxAttributes */);
71990         node.properties = createNodeArray(properties);
71991         return node;
71992     }
71993     ts.createJsxAttributes = createJsxAttributes;
71994     function updateJsxAttributes(node, properties) {
71995         return node.properties !== properties
71996             ? updateNode(createJsxAttributes(properties), node)
71997             : node;
71998     }
71999     ts.updateJsxAttributes = updateJsxAttributes;
72000     function createJsxSpreadAttribute(expression) {
72001         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72002         node.expression = expression;
72003         return node;
72004     }
72005     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72006     function updateJsxSpreadAttribute(node, expression) {
72007         return node.expression !== expression
72008             ? updateNode(createJsxSpreadAttribute(expression), node)
72009             : node;
72010     }
72011     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72012     function createJsxExpression(dotDotDotToken, expression) {
72013         var node = createSynthesizedNode(276 /* JsxExpression */);
72014         node.dotDotDotToken = dotDotDotToken;
72015         node.expression = expression;
72016         return node;
72017     }
72018     ts.createJsxExpression = createJsxExpression;
72019     function updateJsxExpression(node, expression) {
72020         return node.expression !== expression
72021             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72022             : node;
72023     }
72024     ts.updateJsxExpression = updateJsxExpression;
72025     // Clauses
72026     function createCaseClause(expression, statements) {
72027         var node = createSynthesizedNode(277 /* CaseClause */);
72028         node.expression = ts.parenthesizeExpressionForList(expression);
72029         node.statements = createNodeArray(statements);
72030         return node;
72031     }
72032     ts.createCaseClause = createCaseClause;
72033     function updateCaseClause(node, expression, statements) {
72034         return node.expression !== expression
72035             || node.statements !== statements
72036             ? updateNode(createCaseClause(expression, statements), node)
72037             : node;
72038     }
72039     ts.updateCaseClause = updateCaseClause;
72040     function createDefaultClause(statements) {
72041         var node = createSynthesizedNode(278 /* DefaultClause */);
72042         node.statements = createNodeArray(statements);
72043         return node;
72044     }
72045     ts.createDefaultClause = createDefaultClause;
72046     function updateDefaultClause(node, statements) {
72047         return node.statements !== statements
72048             ? updateNode(createDefaultClause(statements), node)
72049             : node;
72050     }
72051     ts.updateDefaultClause = updateDefaultClause;
72052     function createHeritageClause(token, types) {
72053         var node = createSynthesizedNode(279 /* HeritageClause */);
72054         node.token = token;
72055         node.types = createNodeArray(types);
72056         return node;
72057     }
72058     ts.createHeritageClause = createHeritageClause;
72059     function updateHeritageClause(node, types) {
72060         return node.types !== types
72061             ? updateNode(createHeritageClause(node.token, types), node)
72062             : node;
72063     }
72064     ts.updateHeritageClause = updateHeritageClause;
72065     function createCatchClause(variableDeclaration, block) {
72066         var node = createSynthesizedNode(280 /* CatchClause */);
72067         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72068         node.block = block;
72069         return node;
72070     }
72071     ts.createCatchClause = createCatchClause;
72072     function updateCatchClause(node, variableDeclaration, block) {
72073         return node.variableDeclaration !== variableDeclaration
72074             || node.block !== block
72075             ? updateNode(createCatchClause(variableDeclaration, block), node)
72076             : node;
72077     }
72078     ts.updateCatchClause = updateCatchClause;
72079     // Property assignments
72080     function createPropertyAssignment(name, initializer) {
72081         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72082         node.name = asName(name);
72083         node.questionToken = undefined;
72084         node.initializer = ts.parenthesizeExpressionForList(initializer);
72085         return node;
72086     }
72087     ts.createPropertyAssignment = createPropertyAssignment;
72088     function updatePropertyAssignment(node, name, initializer) {
72089         return node.name !== name
72090             || node.initializer !== initializer
72091             ? updateNode(createPropertyAssignment(name, initializer), node)
72092             : node;
72093     }
72094     ts.updatePropertyAssignment = updatePropertyAssignment;
72095     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72096         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72097         node.name = asName(name);
72098         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72099         return node;
72100     }
72101     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72102     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72103         return node.name !== name
72104             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72105             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72106             : node;
72107     }
72108     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72109     function createSpreadAssignment(expression) {
72110         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72111         node.expression = ts.parenthesizeExpressionForList(expression);
72112         return node;
72113     }
72114     ts.createSpreadAssignment = createSpreadAssignment;
72115     function updateSpreadAssignment(node, expression) {
72116         return node.expression !== expression
72117             ? updateNode(createSpreadAssignment(expression), node)
72118             : node;
72119     }
72120     ts.updateSpreadAssignment = updateSpreadAssignment;
72121     // Enum
72122     function createEnumMember(name, initializer) {
72123         var node = createSynthesizedNode(284 /* EnumMember */);
72124         node.name = asName(name);
72125         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72126         return node;
72127     }
72128     ts.createEnumMember = createEnumMember;
72129     function updateEnumMember(node, name, initializer) {
72130         return node.name !== name
72131             || node.initializer !== initializer
72132             ? updateNode(createEnumMember(name, initializer), node)
72133             : node;
72134     }
72135     ts.updateEnumMember = updateEnumMember;
72136     // Top-level nodes
72137     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72138         if (node.statements !== statements ||
72139             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72140             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72141             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72142             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72143             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72144             var updated = createSynthesizedNode(290 /* SourceFile */);
72145             updated.flags |= node.flags;
72146             updated.statements = createNodeArray(statements);
72147             updated.endOfFileToken = node.endOfFileToken;
72148             updated.fileName = node.fileName;
72149             updated.path = node.path;
72150             updated.text = node.text;
72151             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72152             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72153             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72154             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72155             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72156             if (node.amdDependencies !== undefined)
72157                 updated.amdDependencies = node.amdDependencies;
72158             if (node.moduleName !== undefined)
72159                 updated.moduleName = node.moduleName;
72160             if (node.languageVariant !== undefined)
72161                 updated.languageVariant = node.languageVariant;
72162             if (node.renamedDependencies !== undefined)
72163                 updated.renamedDependencies = node.renamedDependencies;
72164             if (node.languageVersion !== undefined)
72165                 updated.languageVersion = node.languageVersion;
72166             if (node.scriptKind !== undefined)
72167                 updated.scriptKind = node.scriptKind;
72168             if (node.externalModuleIndicator !== undefined)
72169                 updated.externalModuleIndicator = node.externalModuleIndicator;
72170             if (node.commonJsModuleIndicator !== undefined)
72171                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72172             if (node.identifiers !== undefined)
72173                 updated.identifiers = node.identifiers;
72174             if (node.nodeCount !== undefined)
72175                 updated.nodeCount = node.nodeCount;
72176             if (node.identifierCount !== undefined)
72177                 updated.identifierCount = node.identifierCount;
72178             if (node.symbolCount !== undefined)
72179                 updated.symbolCount = node.symbolCount;
72180             if (node.parseDiagnostics !== undefined)
72181                 updated.parseDiagnostics = node.parseDiagnostics;
72182             if (node.bindDiagnostics !== undefined)
72183                 updated.bindDiagnostics = node.bindDiagnostics;
72184             if (node.bindSuggestionDiagnostics !== undefined)
72185                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72186             if (node.lineMap !== undefined)
72187                 updated.lineMap = node.lineMap;
72188             if (node.classifiableNames !== undefined)
72189                 updated.classifiableNames = node.classifiableNames;
72190             if (node.resolvedModules !== undefined)
72191                 updated.resolvedModules = node.resolvedModules;
72192             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72193                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72194             if (node.imports !== undefined)
72195                 updated.imports = node.imports;
72196             if (node.moduleAugmentations !== undefined)
72197                 updated.moduleAugmentations = node.moduleAugmentations;
72198             if (node.pragmas !== undefined)
72199                 updated.pragmas = node.pragmas;
72200             if (node.localJsxFactory !== undefined)
72201                 updated.localJsxFactory = node.localJsxFactory;
72202             if (node.localJsxNamespace !== undefined)
72203                 updated.localJsxNamespace = node.localJsxNamespace;
72204             return updateNode(updated, node);
72205         }
72206         return node;
72207     }
72208     ts.updateSourceFileNode = updateSourceFileNode;
72209     /**
72210      * Creates a shallow, memberwise clone of a node for mutation.
72211      */
72212     function getMutableClone(node) {
72213         var clone = getSynthesizedClone(node);
72214         clone.pos = node.pos;
72215         clone.end = node.end;
72216         clone.parent = node.parent;
72217         return clone;
72218     }
72219     ts.getMutableClone = getMutableClone;
72220     // Transformation nodes
72221     /**
72222      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72223      * order to preserve comments.
72224      *
72225      * @param original The original statement.
72226      */
72227     function createNotEmittedStatement(original) {
72228         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72229         node.original = original;
72230         setTextRange(node, original);
72231         return node;
72232     }
72233     ts.createNotEmittedStatement = createNotEmittedStatement;
72234     /**
72235      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72236      * order to properly emit exports.
72237      */
72238     /* @internal */
72239     function createEndOfDeclarationMarker(original) {
72240         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72241         node.emitNode = {};
72242         node.original = original;
72243         return node;
72244     }
72245     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72246     /**
72247      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72248      * order to properly emit exports.
72249      */
72250     /* @internal */
72251     function createMergeDeclarationMarker(original) {
72252         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72253         node.emitNode = {};
72254         node.original = original;
72255         return node;
72256     }
72257     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72258     /**
72259      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72260      * order to preserve comments or sourcemap positions.
72261      *
72262      * @param expression The inner expression to emit.
72263      * @param original The original outer expression.
72264      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72265      */
72266     function createPartiallyEmittedExpression(expression, original) {
72267         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72268         node.expression = expression;
72269         node.original = original;
72270         setTextRange(node, original);
72271         return node;
72272     }
72273     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72274     function updatePartiallyEmittedExpression(node, expression) {
72275         if (node.expression !== expression) {
72276             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72277         }
72278         return node;
72279     }
72280     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72281     function flattenCommaElements(node) {
72282         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72283             if (node.kind === 327 /* CommaListExpression */) {
72284                 return node.elements;
72285             }
72286             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72287                 return [node.left, node.right];
72288             }
72289         }
72290         return node;
72291     }
72292     function createCommaList(elements) {
72293         var node = createSynthesizedNode(327 /* CommaListExpression */);
72294         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72295         return node;
72296     }
72297     ts.createCommaList = createCommaList;
72298     function updateCommaList(node, elements) {
72299         return node.elements !== elements
72300             ? updateNode(createCommaList(elements), node)
72301             : node;
72302     }
72303     ts.updateCommaList = updateCommaList;
72304     /* @internal */
72305     function createSyntheticReferenceExpression(expression, thisArg) {
72306         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72307         node.expression = expression;
72308         node.thisArg = thisArg;
72309         return node;
72310     }
72311     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72312     /* @internal */
72313     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72314         return node.expression !== expression
72315             || node.thisArg !== thisArg
72316             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72317             : node;
72318     }
72319     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72320     function createBundle(sourceFiles, prepends) {
72321         if (prepends === void 0) { prepends = ts.emptyArray; }
72322         var node = ts.createNode(291 /* Bundle */);
72323         node.prepends = prepends;
72324         node.sourceFiles = sourceFiles;
72325         return node;
72326     }
72327     ts.createBundle = createBundle;
72328     var allUnscopedEmitHelpers;
72329     function getAllUnscopedEmitHelpers() {
72330         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72331             ts.valuesHelper,
72332             ts.readHelper,
72333             ts.spreadHelper,
72334             ts.spreadArraysHelper,
72335             ts.restHelper,
72336             ts.decorateHelper,
72337             ts.metadataHelper,
72338             ts.paramHelper,
72339             ts.awaiterHelper,
72340             ts.assignHelper,
72341             ts.awaitHelper,
72342             ts.asyncGeneratorHelper,
72343             ts.asyncDelegator,
72344             ts.asyncValues,
72345             ts.extendsHelper,
72346             ts.templateObjectHelper,
72347             ts.generatorHelper,
72348             ts.importStarHelper,
72349             ts.importDefaultHelper,
72350             ts.classPrivateFieldGetHelper,
72351             ts.classPrivateFieldSetHelper,
72352             ts.createBindingHelper,
72353             ts.setModuleDefaultHelper
72354         ], function (helper) { return helper.name; }));
72355     }
72356     function createUnparsedSource() {
72357         var node = ts.createNode(292 /* UnparsedSource */);
72358         node.prologues = ts.emptyArray;
72359         node.referencedFiles = ts.emptyArray;
72360         node.libReferenceDirectives = ts.emptyArray;
72361         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72362         return node;
72363     }
72364     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72365         var node = createUnparsedSource();
72366         var stripInternal;
72367         var bundleFileInfo;
72368         if (!ts.isString(textOrInputFiles)) {
72369             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72370             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72371             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72372             Object.defineProperties(node, {
72373                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72374                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72375             });
72376             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72377                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72378                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72379                 stripInternal = mapTextOrStripInternal;
72380                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72381                 if (node.oldFileOfCurrentEmit) {
72382                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72383                     return node;
72384                 }
72385             }
72386         }
72387         else {
72388             node.fileName = "";
72389             node.text = textOrInputFiles;
72390             node.sourceMapPath = mapPathOrType;
72391             node.sourceMapText = mapTextOrStripInternal;
72392         }
72393         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72394         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72395         return node;
72396     }
72397     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72398     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72399         var prologues;
72400         var helpers;
72401         var referencedFiles;
72402         var typeReferenceDirectives;
72403         var libReferenceDirectives;
72404         var texts;
72405         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72406             var section = _a[_i];
72407             switch (section.kind) {
72408                 case "prologue" /* Prologue */:
72409                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72410                     break;
72411                 case "emitHelpers" /* EmitHelpers */:
72412                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72413                     break;
72414                 case "no-default-lib" /* NoDefaultLib */:
72415                     node.hasNoDefaultLib = true;
72416                     break;
72417                 case "reference" /* Reference */:
72418                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72419                     break;
72420                 case "type" /* Type */:
72421                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72422                     break;
72423                 case "lib" /* Lib */:
72424                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72425                     break;
72426                 case "prepend" /* Prepend */:
72427                     var prependNode = createUnparsedNode(section, node);
72428                     var prependTexts = void 0;
72429                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72430                         var text = _c[_b];
72431                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72432                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72433                         }
72434                     }
72435                     prependNode.texts = prependTexts || ts.emptyArray;
72436                     (texts || (texts = [])).push(prependNode);
72437                     break;
72438                 case "internal" /* Internal */:
72439                     if (stripInternal) {
72440                         if (!texts)
72441                             texts = [];
72442                         break;
72443                     }
72444                 // falls through
72445                 case "text" /* Text */:
72446                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72447                     break;
72448                 default:
72449                     ts.Debug.assertNever(section);
72450             }
72451         }
72452         node.prologues = prologues || ts.emptyArray;
72453         node.helpers = helpers;
72454         node.referencedFiles = referencedFiles || ts.emptyArray;
72455         node.typeReferenceDirectives = typeReferenceDirectives;
72456         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72457         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72458     }
72459     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72460         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72461         var texts;
72462         var syntheticReferences;
72463         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72464             var section = _a[_i];
72465             switch (section.kind) {
72466                 case "internal" /* Internal */:
72467                 case "text" /* Text */:
72468                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72469                     break;
72470                 case "no-default-lib" /* NoDefaultLib */:
72471                 case "reference" /* Reference */:
72472                 case "type" /* Type */:
72473                 case "lib" /* Lib */:
72474                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72475                     break;
72476                 // Ignore
72477                 case "prologue" /* Prologue */:
72478                 case "emitHelpers" /* EmitHelpers */:
72479                 case "prepend" /* Prepend */:
72480                     break;
72481                 default:
72482                     ts.Debug.assertNever(section);
72483             }
72484         }
72485         node.texts = texts || ts.emptyArray;
72486         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72487         node.syntheticReferences = syntheticReferences;
72488         return node;
72489     }
72490     function mapBundleFileSectionKindToSyntaxKind(kind) {
72491         switch (kind) {
72492             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72493             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72494             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72495             case "text" /* Text */: return 287 /* UnparsedText */;
72496             case "emitHelpers" /* EmitHelpers */:
72497             case "no-default-lib" /* NoDefaultLib */:
72498             case "reference" /* Reference */:
72499             case "type" /* Type */:
72500             case "lib" /* Lib */:
72501                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72502             default:
72503                 return ts.Debug.assertNever(kind);
72504         }
72505     }
72506     function createUnparsedNode(section, parent) {
72507         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72508         node.parent = parent;
72509         node.data = section.data;
72510         return node;
72511     }
72512     function createUnparsedSyntheticReference(section, parent) {
72513         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72514         node.parent = parent;
72515         node.data = section.data;
72516         node.section = section;
72517         return node;
72518     }
72519     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72520         var node = ts.createNode(293 /* InputFiles */);
72521         if (!ts.isString(javascriptTextOrReadFileText)) {
72522             var cache_1 = ts.createMap();
72523             var textGetter_1 = function (path) {
72524                 if (path === undefined)
72525                     return undefined;
72526                 var value = cache_1.get(path);
72527                 if (value === undefined) {
72528                     value = javascriptTextOrReadFileText(path);
72529                     cache_1.set(path, value !== undefined ? value : false);
72530                 }
72531                 return value !== false ? value : undefined;
72532             };
72533             var definedTextGetter_1 = function (path) {
72534                 var result = textGetter_1(path);
72535                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72536             };
72537             var buildInfo_1;
72538             var getAndCacheBuildInfo_1 = function (getText) {
72539                 if (buildInfo_1 === undefined) {
72540                     var result = getText();
72541                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72542                 }
72543                 return buildInfo_1 || undefined;
72544             };
72545             node.javascriptPath = declarationTextOrJavascriptPath;
72546             node.javascriptMapPath = javascriptMapPath;
72547             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72548             node.declarationMapPath = declarationMapPath;
72549             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72550             Object.defineProperties(node, {
72551                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72552                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72553                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72554                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72555                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72556             });
72557         }
72558         else {
72559             node.javascriptText = javascriptTextOrReadFileText;
72560             node.javascriptMapPath = javascriptMapPath;
72561             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72562             node.declarationText = declarationTextOrJavascriptPath;
72563             node.declarationMapPath = declarationMapPath;
72564             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72565             node.javascriptPath = javascriptPath;
72566             node.declarationPath = declarationPath;
72567             node.buildInfoPath = buildInfoPath;
72568             node.buildInfo = buildInfo;
72569             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72570         }
72571         return node;
72572     }
72573     ts.createInputFiles = createInputFiles;
72574     function updateBundle(node, sourceFiles, prepends) {
72575         if (prepends === void 0) { prepends = ts.emptyArray; }
72576         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72577             return createBundle(sourceFiles, prepends);
72578         }
72579         return node;
72580     }
72581     ts.updateBundle = updateBundle;
72582     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72583         return createCall(createFunctionExpression(
72584         /*modifiers*/ undefined, 
72585         /*asteriskToken*/ undefined, 
72586         /*name*/ undefined, 
72587         /*typeParameters*/ undefined, 
72588         /*parameters*/ param ? [param] : [], 
72589         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72590         /*typeArguments*/ undefined, 
72591         /*argumentsArray*/ paramValue ? [paramValue] : []);
72592     }
72593     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72594     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72595         return createCall(createArrowFunction(
72596         /*modifiers*/ undefined, 
72597         /*typeParameters*/ undefined, 
72598         /*parameters*/ param ? [param] : [], 
72599         /*type*/ undefined, 
72600         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72601         /*typeArguments*/ undefined, 
72602         /*argumentsArray*/ paramValue ? [paramValue] : []);
72603     }
72604     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72605     function createComma(left, right) {
72606         return createBinary(left, 27 /* CommaToken */, right);
72607     }
72608     ts.createComma = createComma;
72609     function createLessThan(left, right) {
72610         return createBinary(left, 29 /* LessThanToken */, right);
72611     }
72612     ts.createLessThan = createLessThan;
72613     function createAssignment(left, right) {
72614         return createBinary(left, 62 /* EqualsToken */, right);
72615     }
72616     ts.createAssignment = createAssignment;
72617     function createStrictEquality(left, right) {
72618         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72619     }
72620     ts.createStrictEquality = createStrictEquality;
72621     function createStrictInequality(left, right) {
72622         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72623     }
72624     ts.createStrictInequality = createStrictInequality;
72625     function createAdd(left, right) {
72626         return createBinary(left, 39 /* PlusToken */, right);
72627     }
72628     ts.createAdd = createAdd;
72629     function createSubtract(left, right) {
72630         return createBinary(left, 40 /* MinusToken */, right);
72631     }
72632     ts.createSubtract = createSubtract;
72633     function createPostfixIncrement(operand) {
72634         return createPostfix(operand, 45 /* PlusPlusToken */);
72635     }
72636     ts.createPostfixIncrement = createPostfixIncrement;
72637     function createLogicalAnd(left, right) {
72638         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72639     }
72640     ts.createLogicalAnd = createLogicalAnd;
72641     function createLogicalOr(left, right) {
72642         return createBinary(left, 56 /* BarBarToken */, right);
72643     }
72644     ts.createLogicalOr = createLogicalOr;
72645     function createNullishCoalesce(left, right) {
72646         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72647     }
72648     ts.createNullishCoalesce = createNullishCoalesce;
72649     function createLogicalNot(operand) {
72650         return createPrefix(53 /* ExclamationToken */, operand);
72651     }
72652     ts.createLogicalNot = createLogicalNot;
72653     function createVoidZero() {
72654         return createVoid(createLiteral(0));
72655     }
72656     ts.createVoidZero = createVoidZero;
72657     function createExportDefault(expression) {
72658         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72659     }
72660     ts.createExportDefault = createExportDefault;
72661     function createExternalModuleExport(exportName) {
72662         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72663     }
72664     ts.createExternalModuleExport = createExternalModuleExport;
72665     // Utilities
72666     function asName(name) {
72667         return ts.isString(name) ? createIdentifier(name) : name;
72668     }
72669     function asExpression(value) {
72670         return typeof value === "string" ? createStringLiteral(value) :
72671             typeof value === "number" ? createNumericLiteral("" + value) :
72672                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72673                     value;
72674     }
72675     function asNodeArray(array) {
72676         return array ? createNodeArray(array) : undefined;
72677     }
72678     function asToken(value) {
72679         return typeof value === "number" ? createToken(value) : value;
72680     }
72681     function asEmbeddedStatement(statement) {
72682         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72683     }
72684     /**
72685      * Clears any EmitNode entries from parse-tree nodes.
72686      * @param sourceFile A source file.
72687      */
72688     function disposeEmitNodes(sourceFile) {
72689         // During transformation we may need to annotate a parse tree node with transient
72690         // transformation properties. As parse tree nodes live longer than transformation
72691         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72692         // from these nodes to ensure we do not hold onto entire subtrees just for position
72693         // information. We also need to reset these nodes to a pre-transformation state
72694         // for incremental parsing scenarios so that we do not impact later emit.
72695         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72696         var emitNode = sourceFile && sourceFile.emitNode;
72697         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72698         if (annotatedNodes) {
72699             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72700                 var node = annotatedNodes_1[_i];
72701                 node.emitNode = undefined;
72702             }
72703         }
72704     }
72705     ts.disposeEmitNodes = disposeEmitNodes;
72706     /**
72707      * Associates a node with the current transformation, initializing
72708      * various transient transformation properties.
72709      */
72710     /* @internal */
72711     function getOrCreateEmitNode(node) {
72712         if (!node.emitNode) {
72713             if (ts.isParseTreeNode(node)) {
72714                 // To avoid holding onto transformation artifacts, we keep track of any
72715                 // parse tree node we are annotating. This allows us to clean them up after
72716                 // all transformations have completed.
72717                 if (node.kind === 290 /* SourceFile */) {
72718                     return node.emitNode = { annotatedNodes: [node] };
72719                 }
72720                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72721                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72722             }
72723             node.emitNode = {};
72724         }
72725         return node.emitNode;
72726     }
72727     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72728     /**
72729      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72730      * @internal
72731      */
72732     function removeAllComments(node) {
72733         var emitNode = getOrCreateEmitNode(node);
72734         emitNode.flags |= 1536 /* NoComments */;
72735         emitNode.leadingComments = undefined;
72736         emitNode.trailingComments = undefined;
72737         return node;
72738     }
72739     ts.removeAllComments = removeAllComments;
72740     function setTextRange(range, location) {
72741         if (location) {
72742             range.pos = location.pos;
72743             range.end = location.end;
72744         }
72745         return range;
72746     }
72747     ts.setTextRange = setTextRange;
72748     /**
72749      * Sets flags that control emit behavior of a node.
72750      */
72751     function setEmitFlags(node, emitFlags) {
72752         getOrCreateEmitNode(node).flags = emitFlags;
72753         return node;
72754     }
72755     ts.setEmitFlags = setEmitFlags;
72756     /**
72757      * Sets flags that control emit behavior of a node.
72758      */
72759     /* @internal */
72760     function addEmitFlags(node, emitFlags) {
72761         var emitNode = getOrCreateEmitNode(node);
72762         emitNode.flags = emitNode.flags | emitFlags;
72763         return node;
72764     }
72765     ts.addEmitFlags = addEmitFlags;
72766     /**
72767      * Gets a custom text range to use when emitting source maps.
72768      */
72769     function getSourceMapRange(node) {
72770         var emitNode = node.emitNode;
72771         return (emitNode && emitNode.sourceMapRange) || node;
72772     }
72773     ts.getSourceMapRange = getSourceMapRange;
72774     /**
72775      * Sets a custom text range to use when emitting source maps.
72776      */
72777     function setSourceMapRange(node, range) {
72778         getOrCreateEmitNode(node).sourceMapRange = range;
72779         return node;
72780     }
72781     ts.setSourceMapRange = setSourceMapRange;
72782     var SourceMapSource;
72783     /**
72784      * Create an external source map source file reference
72785      */
72786     function createSourceMapSource(fileName, text, skipTrivia) {
72787         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72788     }
72789     ts.createSourceMapSource = createSourceMapSource;
72790     /**
72791      * Gets the TextRange to use for source maps for a token of a node.
72792      */
72793     function getTokenSourceMapRange(node, token) {
72794         var emitNode = node.emitNode;
72795         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72796         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72797     }
72798     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72799     /**
72800      * Sets the TextRange to use for source maps for a token of a node.
72801      */
72802     function setTokenSourceMapRange(node, token, range) {
72803         var emitNode = getOrCreateEmitNode(node);
72804         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72805         tokenSourceMapRanges[token] = range;
72806         return node;
72807     }
72808     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72809     /**
72810      * Gets a custom text range to use when emitting comments.
72811      */
72812     /*@internal*/
72813     function getStartsOnNewLine(node) {
72814         var emitNode = node.emitNode;
72815         return emitNode && emitNode.startsOnNewLine;
72816     }
72817     ts.getStartsOnNewLine = getStartsOnNewLine;
72818     /**
72819      * Sets a custom text range to use when emitting comments.
72820      */
72821     /*@internal*/
72822     function setStartsOnNewLine(node, newLine) {
72823         getOrCreateEmitNode(node).startsOnNewLine = newLine;
72824         return node;
72825     }
72826     ts.setStartsOnNewLine = setStartsOnNewLine;
72827     /**
72828      * Gets a custom text range to use when emitting comments.
72829      */
72830     function getCommentRange(node) {
72831         var emitNode = node.emitNode;
72832         return (emitNode && emitNode.commentRange) || node;
72833     }
72834     ts.getCommentRange = getCommentRange;
72835     /**
72836      * Sets a custom text range to use when emitting comments.
72837      */
72838     function setCommentRange(node, range) {
72839         getOrCreateEmitNode(node).commentRange = range;
72840         return node;
72841     }
72842     ts.setCommentRange = setCommentRange;
72843     function getSyntheticLeadingComments(node) {
72844         var emitNode = node.emitNode;
72845         return emitNode && emitNode.leadingComments;
72846     }
72847     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
72848     function setSyntheticLeadingComments(node, comments) {
72849         getOrCreateEmitNode(node).leadingComments = comments;
72850         return node;
72851     }
72852     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
72853     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
72854         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72855     }
72856     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
72857     function getSyntheticTrailingComments(node) {
72858         var emitNode = node.emitNode;
72859         return emitNode && emitNode.trailingComments;
72860     }
72861     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
72862     function setSyntheticTrailingComments(node, comments) {
72863         getOrCreateEmitNode(node).trailingComments = comments;
72864         return node;
72865     }
72866     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
72867     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
72868         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72869     }
72870     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
72871     function moveSyntheticComments(node, original) {
72872         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
72873         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
72874         var emit = getOrCreateEmitNode(original);
72875         emit.leadingComments = undefined;
72876         emit.trailingComments = undefined;
72877         return node;
72878     }
72879     ts.moveSyntheticComments = moveSyntheticComments;
72880     /** @internal */
72881     function ignoreSourceNewlines(node) {
72882         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
72883         return node;
72884     }
72885     ts.ignoreSourceNewlines = ignoreSourceNewlines;
72886     /**
72887      * Gets the constant value to emit for an expression.
72888      */
72889     function getConstantValue(node) {
72890         var emitNode = node.emitNode;
72891         return emitNode && emitNode.constantValue;
72892     }
72893     ts.getConstantValue = getConstantValue;
72894     /**
72895      * Sets the constant value to emit for an expression.
72896      */
72897     function setConstantValue(node, value) {
72898         var emitNode = getOrCreateEmitNode(node);
72899         emitNode.constantValue = value;
72900         return node;
72901     }
72902     ts.setConstantValue = setConstantValue;
72903     /**
72904      * Adds an EmitHelper to a node.
72905      */
72906     function addEmitHelper(node, helper) {
72907         var emitNode = getOrCreateEmitNode(node);
72908         emitNode.helpers = ts.append(emitNode.helpers, helper);
72909         return node;
72910     }
72911     ts.addEmitHelper = addEmitHelper;
72912     /**
72913      * Add EmitHelpers to a node.
72914      */
72915     function addEmitHelpers(node, helpers) {
72916         if (ts.some(helpers)) {
72917             var emitNode = getOrCreateEmitNode(node);
72918             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
72919                 var helper = helpers_1[_i];
72920                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
72921             }
72922         }
72923         return node;
72924     }
72925     ts.addEmitHelpers = addEmitHelpers;
72926     /**
72927      * Removes an EmitHelper from a node.
72928      */
72929     function removeEmitHelper(node, helper) {
72930         var emitNode = node.emitNode;
72931         if (emitNode) {
72932             var helpers = emitNode.helpers;
72933             if (helpers) {
72934                 return ts.orderedRemoveItem(helpers, helper);
72935             }
72936         }
72937         return false;
72938     }
72939     ts.removeEmitHelper = removeEmitHelper;
72940     /**
72941      * Gets the EmitHelpers of a node.
72942      */
72943     function getEmitHelpers(node) {
72944         var emitNode = node.emitNode;
72945         return emitNode && emitNode.helpers;
72946     }
72947     ts.getEmitHelpers = getEmitHelpers;
72948     /**
72949      * Moves matching emit helpers from a source node to a target node.
72950      */
72951     function moveEmitHelpers(source, target, predicate) {
72952         var sourceEmitNode = source.emitNode;
72953         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
72954         if (!ts.some(sourceEmitHelpers))
72955             return;
72956         var targetEmitNode = getOrCreateEmitNode(target);
72957         var helpersRemoved = 0;
72958         for (var i = 0; i < sourceEmitHelpers.length; i++) {
72959             var helper = sourceEmitHelpers[i];
72960             if (predicate(helper)) {
72961                 helpersRemoved++;
72962                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
72963             }
72964             else if (helpersRemoved > 0) {
72965                 sourceEmitHelpers[i - helpersRemoved] = helper;
72966             }
72967         }
72968         if (helpersRemoved > 0) {
72969             sourceEmitHelpers.length -= helpersRemoved;
72970         }
72971     }
72972     ts.moveEmitHelpers = moveEmitHelpers;
72973     /* @internal */
72974     function compareEmitHelpers(x, y) {
72975         if (x === y)
72976             return 0 /* EqualTo */;
72977         if (x.priority === y.priority)
72978             return 0 /* EqualTo */;
72979         if (x.priority === undefined)
72980             return 1 /* GreaterThan */;
72981         if (y.priority === undefined)
72982             return -1 /* LessThan */;
72983         return ts.compareValues(x.priority, y.priority);
72984     }
72985     ts.compareEmitHelpers = compareEmitHelpers;
72986     function setOriginalNode(node, original) {
72987         node.original = original;
72988         if (original) {
72989             var emitNode = original.emitNode;
72990             if (emitNode)
72991                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
72992         }
72993         return node;
72994     }
72995     ts.setOriginalNode = setOriginalNode;
72996     function mergeEmitNode(sourceEmitNode, destEmitNode) {
72997         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;
72998         if (!destEmitNode)
72999             destEmitNode = {};
73000         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73001         if (leadingComments)
73002             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73003         if (trailingComments)
73004             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73005         if (flags)
73006             destEmitNode.flags = flags;
73007         if (commentRange)
73008             destEmitNode.commentRange = commentRange;
73009         if (sourceMapRange)
73010             destEmitNode.sourceMapRange = sourceMapRange;
73011         if (tokenSourceMapRanges)
73012             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73013         if (constantValue !== undefined)
73014             destEmitNode.constantValue = constantValue;
73015         if (helpers)
73016             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73017         if (startsOnNewLine !== undefined)
73018             destEmitNode.startsOnNewLine = startsOnNewLine;
73019         return destEmitNode;
73020     }
73021     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73022         if (!destRanges)
73023             destRanges = [];
73024         for (var key in sourceRanges) {
73025             destRanges[key] = sourceRanges[key];
73026         }
73027         return destRanges;
73028     }
73029 })(ts || (ts = {}));
73030 /* @internal */
73031 var ts;
73032 (function (ts) {
73033     ts.nullTransformationContext = {
73034         enableEmitNotification: ts.noop,
73035         enableSubstitution: ts.noop,
73036         endLexicalEnvironment: ts.returnUndefined,
73037         getCompilerOptions: function () { return ({}); },
73038         getEmitHost: ts.notImplemented,
73039         getEmitResolver: ts.notImplemented,
73040         setLexicalEnvironmentFlags: ts.noop,
73041         getLexicalEnvironmentFlags: function () { return 0; },
73042         hoistFunctionDeclaration: ts.noop,
73043         hoistVariableDeclaration: ts.noop,
73044         addInitializationStatement: ts.noop,
73045         isEmitNotificationEnabled: ts.notImplemented,
73046         isSubstitutionEnabled: ts.notImplemented,
73047         onEmitNode: ts.noop,
73048         onSubstituteNode: ts.notImplemented,
73049         readEmitHelpers: ts.notImplemented,
73050         requestEmitHelper: ts.noop,
73051         resumeLexicalEnvironment: ts.noop,
73052         startLexicalEnvironment: ts.noop,
73053         suspendLexicalEnvironment: ts.noop,
73054         addDiagnostic: ts.noop,
73055     };
73056     function createTypeCheck(value, tag) {
73057         return tag === "undefined"
73058             ? ts.createStrictEquality(value, ts.createVoidZero())
73059             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73060     }
73061     ts.createTypeCheck = createTypeCheck;
73062     function createMemberAccessForPropertyName(target, memberName, location) {
73063         if (ts.isComputedPropertyName(memberName)) {
73064             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73065         }
73066         else {
73067             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73068                 ? ts.createPropertyAccess(target, memberName)
73069                 : ts.createElementAccess(target, memberName), memberName);
73070             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73071             return expression;
73072         }
73073     }
73074     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73075     function createFunctionCall(func, thisArg, argumentsList, location) {
73076         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73077         /*typeArguments*/ undefined, __spreadArrays([
73078             thisArg
73079         ], argumentsList)), location);
73080     }
73081     ts.createFunctionCall = createFunctionCall;
73082     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73083         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73084         /*typeArguments*/ undefined, [
73085             thisArg,
73086             argumentsExpression
73087         ]), location);
73088     }
73089     ts.createFunctionApply = createFunctionApply;
73090     function createArraySlice(array, start) {
73091         var argumentsList = [];
73092         if (start !== undefined) {
73093             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73094         }
73095         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73096     }
73097     ts.createArraySlice = createArraySlice;
73098     function createArrayConcat(array, values) {
73099         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73100         /*typeArguments*/ undefined, values);
73101     }
73102     ts.createArrayConcat = createArrayConcat;
73103     function createMathPow(left, right, location) {
73104         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73105         /*typeArguments*/ undefined, [left, right]), location);
73106     }
73107     ts.createMathPow = createMathPow;
73108     function createReactNamespace(reactNamespace, parent) {
73109         // To ensure the emit resolver can properly resolve the namespace, we need to
73110         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73111         // flag and setting a parent node.
73112         var react = ts.createIdentifier(reactNamespace || "React");
73113         react.flags &= ~8 /* Synthesized */;
73114         // Set the parent that is in parse tree
73115         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73116         react.parent = ts.getParseTreeNode(parent);
73117         return react;
73118     }
73119     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73120         if (ts.isQualifiedName(jsxFactory)) {
73121             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73122             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73123             right.escapedText = jsxFactory.right.escapedText;
73124             return ts.createPropertyAccess(left, right);
73125         }
73126         else {
73127             return createReactNamespace(ts.idText(jsxFactory), parent);
73128         }
73129     }
73130     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73131         return jsxFactoryEntity ?
73132             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73133             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73134     }
73135     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73136         var argumentsList = [tagName];
73137         if (props) {
73138             argumentsList.push(props);
73139         }
73140         if (children && children.length > 0) {
73141             if (!props) {
73142                 argumentsList.push(ts.createNull());
73143             }
73144             if (children.length > 1) {
73145                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73146                     var child = children_2[_i];
73147                     startOnNewLine(child);
73148                     argumentsList.push(child);
73149                 }
73150             }
73151             else {
73152                 argumentsList.push(children[0]);
73153             }
73154         }
73155         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73156         /*typeArguments*/ undefined, argumentsList), location);
73157     }
73158     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73159     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73160         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73161         var argumentsList = [tagName];
73162         argumentsList.push(ts.createNull());
73163         if (children && children.length > 0) {
73164             if (children.length > 1) {
73165                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73166                     var child = children_3[_i];
73167                     startOnNewLine(child);
73168                     argumentsList.push(child);
73169                 }
73170             }
73171             else {
73172                 argumentsList.push(children[0]);
73173             }
73174         }
73175         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73176         /*typeArguments*/ undefined, argumentsList), location);
73177     }
73178     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73179     // Helpers
73180     /**
73181      * Gets an identifier for the name of an *unscoped* emit helper.
73182      */
73183     function getUnscopedHelperName(name) {
73184         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73185     }
73186     ts.getUnscopedHelperName = getUnscopedHelperName;
73187     ts.valuesHelper = {
73188         name: "typescript:values",
73189         importName: "__values",
73190         scoped: false,
73191         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            };"
73192     };
73193     function createValuesHelper(context, expression, location) {
73194         context.requestEmitHelper(ts.valuesHelper);
73195         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73196         /*typeArguments*/ undefined, [expression]), location);
73197     }
73198     ts.createValuesHelper = createValuesHelper;
73199     ts.readHelper = {
73200         name: "typescript:read",
73201         importName: "__read",
73202         scoped: false,
73203         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            };"
73204     };
73205     function createReadHelper(context, iteratorRecord, count, location) {
73206         context.requestEmitHelper(ts.readHelper);
73207         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73208         /*typeArguments*/ undefined, count !== undefined
73209             ? [iteratorRecord, ts.createLiteral(count)]
73210             : [iteratorRecord]), location);
73211     }
73212     ts.createReadHelper = createReadHelper;
73213     ts.spreadHelper = {
73214         name: "typescript:spread",
73215         importName: "__spread",
73216         scoped: false,
73217         dependencies: [ts.readHelper],
73218         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            };"
73219     };
73220     function createSpreadHelper(context, argumentList, location) {
73221         context.requestEmitHelper(ts.spreadHelper);
73222         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73223         /*typeArguments*/ undefined, argumentList), location);
73224     }
73225     ts.createSpreadHelper = createSpreadHelper;
73226     ts.spreadArraysHelper = {
73227         name: "typescript:spreadArrays",
73228         importName: "__spreadArrays",
73229         scoped: false,
73230         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            };"
73231     };
73232     function createSpreadArraysHelper(context, argumentList, location) {
73233         context.requestEmitHelper(ts.spreadArraysHelper);
73234         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73235         /*typeArguments*/ undefined, argumentList), location);
73236     }
73237     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73238     // Utilities
73239     function createForOfBindingStatement(node, boundValue) {
73240         if (ts.isVariableDeclarationList(node)) {
73241             var firstDeclaration = ts.first(node.declarations);
73242             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73243             /*typeNode*/ undefined, boundValue);
73244             return ts.setTextRange(ts.createVariableStatement(
73245             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73246             /*location*/ node);
73247         }
73248         else {
73249             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73250             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73251         }
73252     }
73253     ts.createForOfBindingStatement = createForOfBindingStatement;
73254     function insertLeadingStatement(dest, source) {
73255         if (ts.isBlock(dest)) {
73256             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73257         }
73258         else {
73259             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73260         }
73261     }
73262     ts.insertLeadingStatement = insertLeadingStatement;
73263     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73264         if (!outermostLabeledStatement) {
73265             return node;
73266         }
73267         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73268             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73269             : node);
73270         if (afterRestoreLabelCallback) {
73271             afterRestoreLabelCallback(outermostLabeledStatement);
73272         }
73273         return updated;
73274     }
73275     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73276     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73277         var target = ts.skipParentheses(node);
73278         switch (target.kind) {
73279             case 75 /* Identifier */:
73280                 return cacheIdentifiers;
73281             case 104 /* ThisKeyword */:
73282             case 8 /* NumericLiteral */:
73283             case 9 /* BigIntLiteral */:
73284             case 10 /* StringLiteral */:
73285                 return false;
73286             case 192 /* ArrayLiteralExpression */:
73287                 var elements = target.elements;
73288                 if (elements.length === 0) {
73289                     return false;
73290                 }
73291                 return true;
73292             case 193 /* ObjectLiteralExpression */:
73293                 return target.properties.length > 0;
73294             default:
73295                 return true;
73296         }
73297     }
73298     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73299         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73300         var callee = skipOuterExpressions(expression, 15 /* All */);
73301         var thisArg;
73302         var target;
73303         if (ts.isSuperProperty(callee)) {
73304             thisArg = ts.createThis();
73305             target = callee;
73306         }
73307         else if (callee.kind === 102 /* SuperKeyword */) {
73308             thisArg = ts.createThis();
73309             target = languageVersion < 2 /* ES2015 */
73310                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73311                 : callee;
73312         }
73313         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73314             thisArg = ts.createVoidZero();
73315             target = parenthesizeForAccess(callee);
73316         }
73317         else {
73318             switch (callee.kind) {
73319                 case 194 /* PropertyAccessExpression */: {
73320                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73321                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73322                         thisArg = ts.createTempVariable(recordTempVariable);
73323                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73324                         ts.setTextRange(target, callee);
73325                     }
73326                     else {
73327                         thisArg = callee.expression;
73328                         target = callee;
73329                     }
73330                     break;
73331                 }
73332                 case 195 /* ElementAccessExpression */: {
73333                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73334                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73335                         thisArg = ts.createTempVariable(recordTempVariable);
73336                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73337                         ts.setTextRange(target, callee);
73338                     }
73339                     else {
73340                         thisArg = callee.expression;
73341                         target = callee;
73342                     }
73343                     break;
73344                 }
73345                 default: {
73346                     // for `a()` target is `a` and thisArg is `void 0`
73347                     thisArg = ts.createVoidZero();
73348                     target = parenthesizeForAccess(expression);
73349                     break;
73350                 }
73351             }
73352         }
73353         return { target: target, thisArg: thisArg };
73354     }
73355     ts.createCallBinding = createCallBinding;
73356     function inlineExpressions(expressions) {
73357         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73358         // stack size exceeded" errors.
73359         return expressions.length > 10
73360             ? ts.createCommaList(expressions)
73361             : ts.reduceLeft(expressions, ts.createComma);
73362     }
73363     ts.inlineExpressions = inlineExpressions;
73364     function createExpressionFromEntityName(node) {
73365         if (ts.isQualifiedName(node)) {
73366             var left = createExpressionFromEntityName(node.left);
73367             var right = ts.getMutableClone(node.right);
73368             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73369         }
73370         else {
73371             return ts.getMutableClone(node);
73372         }
73373     }
73374     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73375     function createExpressionForPropertyName(memberName) {
73376         if (ts.isIdentifier(memberName)) {
73377             return ts.createLiteral(memberName);
73378         }
73379         else if (ts.isComputedPropertyName(memberName)) {
73380             return ts.getMutableClone(memberName.expression);
73381         }
73382         else {
73383             return ts.getMutableClone(memberName);
73384         }
73385     }
73386     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73387     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73388         if (property.name && ts.isPrivateIdentifier(property.name)) {
73389             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73390         }
73391         switch (property.kind) {
73392             case 163 /* GetAccessor */:
73393             case 164 /* SetAccessor */:
73394                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73395             case 281 /* PropertyAssignment */:
73396                 return createExpressionForPropertyAssignment(property, receiver);
73397             case 282 /* ShorthandPropertyAssignment */:
73398                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73399             case 161 /* MethodDeclaration */:
73400                 return createExpressionForMethodDeclaration(property, receiver);
73401         }
73402     }
73403     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73404     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73405         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73406         if (property === firstAccessor) {
73407             var properties_7 = [];
73408             if (getAccessor) {
73409                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73410                 /*asteriskToken*/ undefined, 
73411                 /*name*/ undefined, 
73412                 /*typeParameters*/ undefined, getAccessor.parameters, 
73413                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73414                 );
73415                 ts.setTextRange(getterFunction, getAccessor);
73416                 ts.setOriginalNode(getterFunction, getAccessor);
73417                 var getter = ts.createPropertyAssignment("get", getterFunction);
73418                 properties_7.push(getter);
73419             }
73420             if (setAccessor) {
73421                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73422                 /*asteriskToken*/ undefined, 
73423                 /*name*/ undefined, 
73424                 /*typeParameters*/ undefined, setAccessor.parameters, 
73425                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73426                 );
73427                 ts.setTextRange(setterFunction, setAccessor);
73428                 ts.setOriginalNode(setterFunction, setAccessor);
73429                 var setter = ts.createPropertyAssignment("set", setterFunction);
73430                 properties_7.push(setter);
73431             }
73432             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73433             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73434             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73435             /*typeArguments*/ undefined, [
73436                 receiver,
73437                 createExpressionForPropertyName(property.name),
73438                 ts.createObjectLiteral(properties_7, multiLine)
73439             ]), 
73440             /*location*/ firstAccessor);
73441             return ts.aggregateTransformFlags(expression);
73442         }
73443         return undefined;
73444     }
73445     function createExpressionForPropertyAssignment(property, receiver) {
73446         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73447     }
73448     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73449         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73450         /*location*/ property), 
73451         /*original*/ property));
73452     }
73453     function createExpressionForMethodDeclaration(method, receiver) {
73454         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, 
73455         /*name*/ undefined, 
73456         /*typeParameters*/ undefined, method.parameters, 
73457         /*type*/ undefined, method.body // TODO: GH#18217
73458         ), 
73459         /*location*/ method), 
73460         /*original*/ method)), 
73461         /*location*/ method), 
73462         /*original*/ method));
73463     }
73464     /**
73465      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73466      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73467      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73468      * expression. An internal name will also *never* be renamed due to a collision with a block
73469      * scoped variable.
73470      *
73471      * @param node The declaration.
73472      * @param allowComments A value indicating whether comments may be emitted for the name.
73473      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73474      */
73475     function getInternalName(node, allowComments, allowSourceMaps) {
73476         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73477     }
73478     ts.getInternalName = getInternalName;
73479     /**
73480      * Gets whether an identifier should only be referred to by its internal name.
73481      */
73482     function isInternalName(node) {
73483         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73484     }
73485     ts.isInternalName = isInternalName;
73486     /**
73487      * Gets the local name of a declaration. This is primarily used for declarations that can be
73488      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73489      * local name will *never* be prefixed with an module or namespace export modifier like
73490      * "exports." when emitted as an expression.
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 getLocalName(node, allowComments, allowSourceMaps) {
73497         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73498     }
73499     ts.getLocalName = getLocalName;
73500     /**
73501      * Gets whether an identifier should only be referred to by its local name.
73502      */
73503     function isLocalName(node) {
73504         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73505     }
73506     ts.isLocalName = isLocalName;
73507     /**
73508      * Gets the export 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). An
73510      * export name will *always* be prefixed with an module or namespace export modifier like
73511      * `"exports."` when emitted as an expression if the name points to an exported symbol.
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 getExportName(node, allowComments, allowSourceMaps) {
73518         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73519     }
73520     ts.getExportName = getExportName;
73521     /**
73522      * Gets whether an identifier should only be referred to by its export representation if the
73523      * name points to an exported symbol.
73524      */
73525     function isExportName(node) {
73526         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73527     }
73528     ts.isExportName = isExportName;
73529     /**
73530      * Gets the name of a declaration for use in declarations.
73531      *
73532      * @param node The declaration.
73533      * @param allowComments A value indicating whether comments may be emitted for the name.
73534      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73535      */
73536     function getDeclarationName(node, allowComments, allowSourceMaps) {
73537         return getName(node, allowComments, allowSourceMaps);
73538     }
73539     ts.getDeclarationName = getDeclarationName;
73540     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73541         if (emitFlags === void 0) { emitFlags = 0; }
73542         var nodeName = ts.getNameOfDeclaration(node);
73543         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73544             var name = ts.getMutableClone(nodeName);
73545             emitFlags |= ts.getEmitFlags(nodeName);
73546             if (!allowSourceMaps)
73547                 emitFlags |= 48 /* NoSourceMap */;
73548             if (!allowComments)
73549                 emitFlags |= 1536 /* NoComments */;
73550             if (emitFlags)
73551                 ts.setEmitFlags(name, emitFlags);
73552             return name;
73553         }
73554         return ts.getGeneratedNameForNode(node);
73555     }
73556     /**
73557      * Gets the exported name of a declaration for use in expressions.
73558      *
73559      * An exported name will *always* be prefixed with an module or namespace export modifier like
73560      * "exports." if the name points to an exported symbol.
73561      *
73562      * @param ns The namespace identifier.
73563      * @param node The declaration.
73564      * @param allowComments A value indicating whether comments may be emitted for the name.
73565      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73566      */
73567     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73568         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73569             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73570         }
73571         return getExportName(node, allowComments, allowSourceMaps);
73572     }
73573     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73574     /**
73575      * Gets a namespace-qualified name for use in expressions.
73576      *
73577      * @param ns The namespace identifier.
73578      * @param name The name.
73579      * @param allowComments A value indicating whether comments may be emitted for the name.
73580      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73581      */
73582     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73583         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73584         ts.setTextRange(qualifiedName, name);
73585         var emitFlags = 0;
73586         if (!allowSourceMaps)
73587             emitFlags |= 48 /* NoSourceMap */;
73588         if (!allowComments)
73589             emitFlags |= 1536 /* NoComments */;
73590         if (emitFlags)
73591             ts.setEmitFlags(qualifiedName, emitFlags);
73592         return qualifiedName;
73593     }
73594     ts.getNamespaceMemberName = getNamespaceMemberName;
73595     function convertToFunctionBody(node, multiLine) {
73596         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73597     }
73598     ts.convertToFunctionBody = convertToFunctionBody;
73599     function convertFunctionDeclarationToExpression(node) {
73600         if (!node.body)
73601             return ts.Debug.fail();
73602         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73603         ts.setOriginalNode(updated, node);
73604         ts.setTextRange(updated, node);
73605         if (ts.getStartsOnNewLine(node)) {
73606             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73607         }
73608         ts.aggregateTransformFlags(updated);
73609         return updated;
73610     }
73611     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73612     function isUseStrictPrologue(node) {
73613         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73614     }
73615     /**
73616      * Add any necessary prologue-directives into target statement-array.
73617      * The function needs to be called during each transformation step.
73618      * This function needs to be called whenever we transform the statement
73619      * list of a source file, namespace, or function-like body.
73620      *
73621      * @param target: result statements array
73622      * @param source: origin statements array
73623      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73624      * @param visitor: Optional callback used to visit any custom prologue directives.
73625      */
73626     function addPrologue(target, source, ensureUseStrict, visitor) {
73627         var offset = addStandardPrologue(target, source, ensureUseStrict);
73628         return addCustomPrologue(target, source, offset, visitor);
73629     }
73630     ts.addPrologue = addPrologue;
73631     /**
73632      * Add just the standard (string-expression) prologue-directives into target statement-array.
73633      * The function needs to be called during each transformation step.
73634      * This function needs to be called whenever we transform the statement
73635      * list of a source file, namespace, or function-like body.
73636      */
73637     function addStandardPrologue(target, source, ensureUseStrict) {
73638         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73639         var foundUseStrict = false;
73640         var statementOffset = 0;
73641         var numStatements = source.length;
73642         while (statementOffset < numStatements) {
73643             var statement = source[statementOffset];
73644             if (ts.isPrologueDirective(statement)) {
73645                 if (isUseStrictPrologue(statement)) {
73646                     foundUseStrict = true;
73647                 }
73648                 target.push(statement);
73649             }
73650             else {
73651                 break;
73652             }
73653             statementOffset++;
73654         }
73655         if (ensureUseStrict && !foundUseStrict) {
73656             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73657         }
73658         return statementOffset;
73659     }
73660     ts.addStandardPrologue = addStandardPrologue;
73661     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73662         if (filter === void 0) { filter = ts.returnTrue; }
73663         var numStatements = source.length;
73664         while (statementOffset !== undefined && statementOffset < numStatements) {
73665             var statement = source[statementOffset];
73666             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73667                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73668             }
73669             else {
73670                 break;
73671             }
73672             statementOffset++;
73673         }
73674         return statementOffset;
73675     }
73676     ts.addCustomPrologue = addCustomPrologue;
73677     function findUseStrictPrologue(statements) {
73678         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73679             var statement = statements_4[_i];
73680             if (ts.isPrologueDirective(statement)) {
73681                 if (isUseStrictPrologue(statement)) {
73682                     return statement;
73683                 }
73684             }
73685             else {
73686                 break;
73687             }
73688         }
73689         return undefined;
73690     }
73691     ts.findUseStrictPrologue = findUseStrictPrologue;
73692     function startsWithUseStrict(statements) {
73693         var firstStatement = ts.firstOrUndefined(statements);
73694         return firstStatement !== undefined
73695             && ts.isPrologueDirective(firstStatement)
73696             && isUseStrictPrologue(firstStatement);
73697     }
73698     ts.startsWithUseStrict = startsWithUseStrict;
73699     /**
73700      * Ensures "use strict" directive is added
73701      *
73702      * @param statements An array of statements
73703      */
73704     function ensureUseStrict(statements) {
73705         var foundUseStrict = findUseStrictPrologue(statements);
73706         if (!foundUseStrict) {
73707             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73708                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73709             ], statements)), statements);
73710         }
73711         return statements;
73712     }
73713     ts.ensureUseStrict = ensureUseStrict;
73714     /**
73715      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73716      * order of operations.
73717      *
73718      * @param binaryOperator The operator for the BinaryExpression.
73719      * @param operand The operand for the BinaryExpression.
73720      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73721      *                           BinaryExpression.
73722      */
73723     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73724         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73725         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73726         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73727             return operand;
73728         }
73729         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73730             ? ts.createParen(operand)
73731             : operand;
73732     }
73733     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73734     /**
73735      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73736      *
73737      * @param binaryOperator The operator for the BinaryExpression.
73738      * @param operand The operand for the BinaryExpression.
73739      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73740      *                           BinaryExpression.
73741      */
73742     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73743         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73744         // intent of the expression. For example, if the operand is `a + b` and the operator is
73745         // `*`, then we need to parenthesize the operand to preserve the intended order of
73746         // operations: `(a + b) * x`.
73747         //
73748         // If the operand has higher precedence, then it does not need to be parenthesized. For
73749         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73750         // parenthesize to preserve the intended order of operations: `a * b + x`.
73751         //
73752         // If the operand has the same precedence, then we need to check the associativity of
73753         // the operator based on whether this is the left or right operand of the expression.
73754         //
73755         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73756         // to preserve the intended order of operations: `x * (a / d)`
73757         //
73758         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73759         // the intended order of operations: `(a ** b) ** c`
73760         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73761         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73762         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73763         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73764             // We need to parenthesize arrow functions on the right side to avoid it being
73765             // parsed as parenthesized expression: `a && (() => {})`
73766             return true;
73767         }
73768         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73769         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73770             case -1 /* LessThan */:
73771                 // If the operand is the right side of a right-associative binary operation
73772                 // and is a yield expression, then we do not need parentheses.
73773                 if (!isLeftSideOfBinary
73774                     && binaryOperatorAssociativity === 1 /* Right */
73775                     && operand.kind === 212 /* YieldExpression */) {
73776                     return false;
73777                 }
73778                 return true;
73779             case 1 /* GreaterThan */:
73780                 return false;
73781             case 0 /* EqualTo */:
73782                 if (isLeftSideOfBinary) {
73783                     // No need to parenthesize the left operand when the binary operator is
73784                     // left associative:
73785                     //  (a*b)/x    -> a*b/x
73786                     //  (a**b)/x   -> a**b/x
73787                     //
73788                     // Parentheses are needed for the left operand when the binary operator is
73789                     // right associative:
73790                     //  (a/b)**x   -> (a/b)**x
73791                     //  (a**b)**x  -> (a**b)**x
73792                     return binaryOperatorAssociativity === 1 /* Right */;
73793                 }
73794                 else {
73795                     if (ts.isBinaryExpression(emittedOperand)
73796                         && emittedOperand.operatorToken.kind === binaryOperator) {
73797                         // No need to parenthesize the right operand when the binary operator and
73798                         // operand are the same and one of the following:
73799                         //  x*(a*b)     => x*a*b
73800                         //  x|(a|b)     => x|a|b
73801                         //  x&(a&b)     => x&a&b
73802                         //  x^(a^b)     => x^a^b
73803                         if (operatorHasAssociativeProperty(binaryOperator)) {
73804                             return false;
73805                         }
73806                         // No need to parenthesize the right operand when the binary operator
73807                         // is plus (+) if both the left and right operands consist solely of either
73808                         // literals of the same kind or binary plus (+) expressions for literals of
73809                         // the same kind (recursively).
73810                         //  "a"+(1+2)       => "a"+(1+2)
73811                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73812                         if (binaryOperator === 39 /* PlusToken */) {
73813                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73814                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73815                                 return false;
73816                             }
73817                         }
73818                     }
73819                     // No need to parenthesize the right operand when the operand is right
73820                     // associative:
73821                     //  x/(a**b)    -> x/a**b
73822                     //  x**(a**b)   -> x**a**b
73823                     //
73824                     // Parentheses are needed for the right operand when the operand is left
73825                     // associative:
73826                     //  x/(a*b)     -> x/(a*b)
73827                     //  x**(a/b)    -> x**(a/b)
73828                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
73829                     return operandAssociativity === 0 /* Left */;
73830                 }
73831         }
73832     }
73833     /**
73834      * Determines whether a binary operator is mathematically associative.
73835      *
73836      * @param binaryOperator The binary operator.
73837      */
73838     function operatorHasAssociativeProperty(binaryOperator) {
73839         // The following operators are associative in JavaScript:
73840         //  (a*b)*c     -> a*(b*c)  -> a*b*c
73841         //  (a|b)|c     -> a|(b|c)  -> a|b|c
73842         //  (a&b)&c     -> a&(b&c)  -> a&b&c
73843         //  (a^b)^c     -> a^(b^c)  -> a^b^c
73844         //
73845         // While addition is associative in mathematics, JavaScript's `+` is not
73846         // guaranteed to be associative as it is overloaded with string concatenation.
73847         return binaryOperator === 41 /* AsteriskToken */
73848             || binaryOperator === 51 /* BarToken */
73849             || binaryOperator === 50 /* AmpersandToken */
73850             || binaryOperator === 52 /* CaretToken */;
73851     }
73852     /**
73853      * This function determines whether an expression consists of a homogeneous set of
73854      * literal expressions or binary plus expressions that all share the same literal kind.
73855      * It is used to determine whether the right-hand operand of a binary plus expression can be
73856      * emitted without parentheses.
73857      */
73858     function getLiteralKindOfBinaryPlusOperand(node) {
73859         node = ts.skipPartiallyEmittedExpressions(node);
73860         if (ts.isLiteralKind(node.kind)) {
73861             return node.kind;
73862         }
73863         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
73864             if (node.cachedLiteralKind !== undefined) {
73865                 return node.cachedLiteralKind;
73866             }
73867             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
73868             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
73869                 0 /* Unknown */;
73870             node.cachedLiteralKind = literalKind;
73871             return literalKind;
73872         }
73873         return 0 /* Unknown */;
73874     }
73875     function parenthesizeForConditionalHead(condition) {
73876         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
73877         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
73878         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
73879         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
73880             return ts.createParen(condition);
73881         }
73882         return condition;
73883     }
73884     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
73885     function parenthesizeSubexpressionOfConditionalExpression(e) {
73886         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
73887         // so in case when comma expression is introduced as a part of previous transformations
73888         // if should be wrapped in parens since comma operator has the lowest precedence
73889         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
73890         return isCommaSequence(emittedExpression)
73891             ? ts.createParen(e)
73892             : e;
73893     }
73894     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
73895     /**
73896      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
73897      *  has a lookahead restriction for `function`, `async function`, and `class`.
73898      *
73899      * Basically, that means we need to parenthesize in the following cases:
73900      *
73901      * - BinaryExpression of CommaToken
73902      * - CommaList (synthetic list of multiple comma expressions)
73903      * - FunctionExpression
73904      * - ClassExpression
73905      */
73906     function parenthesizeDefaultExpression(e) {
73907         var check = ts.skipPartiallyEmittedExpressions(e);
73908         var needsParens = isCommaSequence(check);
73909         if (!needsParens) {
73910             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
73911                 case 214 /* ClassExpression */:
73912                 case 201 /* FunctionExpression */:
73913                     needsParens = true;
73914             }
73915         }
73916         return needsParens ? ts.createParen(e) : e;
73917     }
73918     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
73919     /**
73920      * Wraps an expression in parentheses if it is needed in order to use the expression
73921      * as the expression of a NewExpression node.
73922      *
73923      * @param expression The Expression node.
73924      */
73925     function parenthesizeForNew(expression) {
73926         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
73927         switch (leftmostExpr.kind) {
73928             case 196 /* CallExpression */:
73929                 return ts.createParen(expression);
73930             case 197 /* NewExpression */:
73931                 return !leftmostExpr.arguments
73932                     ? ts.createParen(expression)
73933                     : expression;
73934         }
73935         return parenthesizeForAccess(expression);
73936     }
73937     ts.parenthesizeForNew = parenthesizeForNew;
73938     /**
73939      * Wraps an expression in parentheses if it is needed in order to use the expression for
73940      * property or element access.
73941      *
73942      * @param expr The expression node.
73943      */
73944     function parenthesizeForAccess(expression) {
73945         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
73946         // to parenthesize the expression before a dot. The known exception is:
73947         //
73948         //    NewExpression:
73949         //       new C.x        -> not the same as (new C).x
73950         //
73951         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73952         if (ts.isLeftHandSideExpression(emittedExpression)
73953             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
73954             return expression;
73955         }
73956         return ts.setTextRange(ts.createParen(expression), expression);
73957     }
73958     ts.parenthesizeForAccess = parenthesizeForAccess;
73959     function parenthesizePostfixOperand(operand) {
73960         return ts.isLeftHandSideExpression(operand)
73961             ? operand
73962             : ts.setTextRange(ts.createParen(operand), operand);
73963     }
73964     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
73965     function parenthesizePrefixOperand(operand) {
73966         return ts.isUnaryExpression(operand)
73967             ? operand
73968             : ts.setTextRange(ts.createParen(operand), operand);
73969     }
73970     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
73971     function parenthesizeListElements(elements) {
73972         var result;
73973         for (var i = 0; i < elements.length; i++) {
73974             var element = parenthesizeExpressionForList(elements[i]);
73975             if (result !== undefined || element !== elements[i]) {
73976                 if (result === undefined) {
73977                     result = elements.slice(0, i);
73978                 }
73979                 result.push(element);
73980             }
73981         }
73982         if (result !== undefined) {
73983             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
73984         }
73985         return elements;
73986     }
73987     ts.parenthesizeListElements = parenthesizeListElements;
73988     function parenthesizeExpressionForList(expression) {
73989         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73990         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
73991         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
73992         return expressionPrecedence > commaPrecedence
73993             ? expression
73994             : ts.setTextRange(ts.createParen(expression), expression);
73995     }
73996     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
73997     function parenthesizeExpressionForExpressionStatement(expression) {
73998         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73999         if (ts.isCallExpression(emittedExpression)) {
74000             var callee = emittedExpression.expression;
74001             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74002             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74003                 var mutableCall = ts.getMutableClone(emittedExpression);
74004                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74005                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74006             }
74007         }
74008         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74009         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74010             return ts.setTextRange(ts.createParen(expression), expression);
74011         }
74012         return expression;
74013     }
74014     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74015     function parenthesizeConditionalTypeMember(member) {
74016         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74017     }
74018     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74019     function parenthesizeElementTypeMember(member) {
74020         switch (member.kind) {
74021             case 178 /* UnionType */:
74022             case 179 /* IntersectionType */:
74023             case 170 /* FunctionType */:
74024             case 171 /* ConstructorType */:
74025                 return ts.createParenthesizedType(member);
74026         }
74027         return parenthesizeConditionalTypeMember(member);
74028     }
74029     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74030     function parenthesizeArrayTypeMember(member) {
74031         switch (member.kind) {
74032             case 172 /* TypeQuery */:
74033             case 184 /* TypeOperator */:
74034             case 181 /* InferType */:
74035                 return ts.createParenthesizedType(member);
74036         }
74037         return parenthesizeElementTypeMember(member);
74038     }
74039     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74040     function parenthesizeElementTypeMembers(members) {
74041         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74042     }
74043     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74044     function parenthesizeTypeParameters(typeParameters) {
74045         if (ts.some(typeParameters)) {
74046             var params = [];
74047             for (var i = 0; i < typeParameters.length; ++i) {
74048                 var entry = typeParameters[i];
74049                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74050                     ts.createParenthesizedType(entry) :
74051                     entry);
74052             }
74053             return ts.createNodeArray(params);
74054         }
74055     }
74056     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74057     function getLeftmostExpression(node, stopAtCallExpressions) {
74058         while (true) {
74059             switch (node.kind) {
74060                 case 208 /* PostfixUnaryExpression */:
74061                     node = node.operand;
74062                     continue;
74063                 case 209 /* BinaryExpression */:
74064                     node = node.left;
74065                     continue;
74066                 case 210 /* ConditionalExpression */:
74067                     node = node.condition;
74068                     continue;
74069                 case 198 /* TaggedTemplateExpression */:
74070                     node = node.tag;
74071                     continue;
74072                 case 196 /* CallExpression */:
74073                     if (stopAtCallExpressions) {
74074                         return node;
74075                     }
74076                 // falls through
74077                 case 217 /* AsExpression */:
74078                 case 195 /* ElementAccessExpression */:
74079                 case 194 /* PropertyAccessExpression */:
74080                 case 218 /* NonNullExpression */:
74081                 case 326 /* PartiallyEmittedExpression */:
74082                     node = node.expression;
74083                     continue;
74084             }
74085             return node;
74086         }
74087     }
74088     ts.getLeftmostExpression = getLeftmostExpression;
74089     function parenthesizeConciseBody(body) {
74090         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74091             return ts.setTextRange(ts.createParen(body), body);
74092         }
74093         return body;
74094     }
74095     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74096     function isCommaSequence(node) {
74097         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74098             node.kind === 327 /* CommaListExpression */;
74099     }
74100     ts.isCommaSequence = isCommaSequence;
74101     var OuterExpressionKinds;
74102     (function (OuterExpressionKinds) {
74103         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74104         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74105         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74106         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74107         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74108         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74109     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74110     function isOuterExpression(node, kinds) {
74111         if (kinds === void 0) { kinds = 15 /* All */; }
74112         switch (node.kind) {
74113             case 200 /* ParenthesizedExpression */:
74114                 return (kinds & 1 /* Parentheses */) !== 0;
74115             case 199 /* TypeAssertionExpression */:
74116             case 217 /* AsExpression */:
74117                 return (kinds & 2 /* TypeAssertions */) !== 0;
74118             case 218 /* NonNullExpression */:
74119                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74120             case 326 /* PartiallyEmittedExpression */:
74121                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74122         }
74123         return false;
74124     }
74125     ts.isOuterExpression = isOuterExpression;
74126     function skipOuterExpressions(node, kinds) {
74127         if (kinds === void 0) { kinds = 15 /* All */; }
74128         while (isOuterExpression(node, kinds)) {
74129             node = node.expression;
74130         }
74131         return node;
74132     }
74133     ts.skipOuterExpressions = skipOuterExpressions;
74134     function skipAssertions(node) {
74135         return skipOuterExpressions(node, 6 /* Assertions */);
74136     }
74137     ts.skipAssertions = skipAssertions;
74138     function updateOuterExpression(outerExpression, expression) {
74139         switch (outerExpression.kind) {
74140             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74141             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74142             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74143             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74144             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74145         }
74146     }
74147     /**
74148      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74149      *
74150      * A parenthesized expression can be ignored when all of the following are true:
74151      *
74152      * - It's `pos` and `end` are not -1
74153      * - It does not have a custom source map range
74154      * - It does not have a custom comment range
74155      * - It does not have synthetic leading or trailing comments
74156      *
74157      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74158      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74159      * the containing expression is created/updated.
74160      */
74161     function isIgnorableParen(node) {
74162         return node.kind === 200 /* ParenthesizedExpression */
74163             && ts.nodeIsSynthesized(node)
74164             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74165             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74166             && !ts.some(ts.getSyntheticLeadingComments(node))
74167             && !ts.some(ts.getSyntheticTrailingComments(node));
74168     }
74169     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74170         if (kinds === void 0) { kinds = 15 /* All */; }
74171         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74172             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74173         }
74174         return innerExpression;
74175     }
74176     ts.recreateOuterExpressions = recreateOuterExpressions;
74177     function startOnNewLine(node) {
74178         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74179     }
74180     ts.startOnNewLine = startOnNewLine;
74181     function getExternalHelpersModuleName(node) {
74182         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74183         var emitNode = parseNode && parseNode.emitNode;
74184         return emitNode && emitNode.externalHelpersModuleName;
74185     }
74186     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74187     function hasRecordedExternalHelpers(sourceFile) {
74188         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74189         var emitNode = parseNode && parseNode.emitNode;
74190         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74191     }
74192     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74193     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74194         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74195             var namedBindings = void 0;
74196             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74197             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74198                 // use named imports
74199                 var helpers = ts.getEmitHelpers(sourceFile);
74200                 if (helpers) {
74201                     var helperNames = [];
74202                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74203                         var helper = helpers_2[_i];
74204                         if (!helper.scoped) {
74205                             var importName = helper.importName;
74206                             if (importName) {
74207                                 ts.pushIfUnique(helperNames, importName);
74208                             }
74209                         }
74210                     }
74211                     if (ts.some(helperNames)) {
74212                         helperNames.sort(ts.compareStringsCaseSensitive);
74213                         // Alias the imports if the names are used somewhere in the file.
74214                         // NOTE: We don't need to care about global import collisions as this is a module.
74215                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74216                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74217                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74218                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74219                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74220                         emitNode.externalHelpers = true;
74221                     }
74222                 }
74223             }
74224             else {
74225                 // use a namespace import
74226                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74227                 if (externalHelpersModuleName) {
74228                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74229                 }
74230             }
74231             if (namedBindings) {
74232                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74233                 /*decorators*/ undefined, 
74234                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74235                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74236                 return externalHelpersImportDeclaration;
74237             }
74238         }
74239     }
74240     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74241     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74242         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74243             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74244             if (externalHelpersModuleName) {
74245                 return externalHelpersModuleName;
74246             }
74247             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74248             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74249                 && moduleKind !== ts.ModuleKind.System
74250                 && moduleKind < ts.ModuleKind.ES2015;
74251             if (!create) {
74252                 var helpers = ts.getEmitHelpers(node);
74253                 if (helpers) {
74254                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74255                         var helper = helpers_3[_i];
74256                         if (!helper.scoped) {
74257                             create = true;
74258                             break;
74259                         }
74260                     }
74261                 }
74262             }
74263             if (create) {
74264                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74265                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74266                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74267             }
74268         }
74269     }
74270     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74271     /**
74272      * Get the name of that target module from an import or export declaration
74273      */
74274     function getLocalNameForExternalImport(node, sourceFile) {
74275         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74276         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74277             var name = namespaceDeclaration.name;
74278             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74279         }
74280         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74281             return ts.getGeneratedNameForNode(node);
74282         }
74283         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74284             return ts.getGeneratedNameForNode(node);
74285         }
74286         return undefined;
74287     }
74288     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74289     /**
74290      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74291      * The emitted output name can be different from the input if:
74292      *  1. The module has a /// <amd-module name="<new name>" />
74293      *  2. --out or --outFile is used, making the name relative to the rootDir
74294      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74295      * Otherwise, a new StringLiteral node representing the module name will be returned.
74296      */
74297     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74298         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74299         if (moduleName.kind === 10 /* StringLiteral */) {
74300             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74301                 || tryRenameExternalModule(moduleName, sourceFile)
74302                 || ts.getSynthesizedClone(moduleName);
74303         }
74304         return undefined;
74305     }
74306     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74307     /**
74308      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74309      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74310      */
74311     function tryRenameExternalModule(moduleName, sourceFile) {
74312         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74313         return rename && ts.createLiteral(rename);
74314     }
74315     /**
74316      * Get the name of a module as should be written in the emitted output.
74317      * The emitted output name can be different from the input if:
74318      *  1. The module has a /// <amd-module name="<new name>" />
74319      *  2. --out or --outFile is used, making the name relative to the rootDir
74320      * Otherwise, a new StringLiteral node representing the module name will be returned.
74321      */
74322     function tryGetModuleNameFromFile(file, host, options) {
74323         if (!file) {
74324             return undefined;
74325         }
74326         if (file.moduleName) {
74327             return ts.createLiteral(file.moduleName);
74328         }
74329         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74330             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74331         }
74332         return undefined;
74333     }
74334     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74335     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74336         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74337     }
74338     /**
74339      * Gets the initializer of an BindingOrAssignmentElement.
74340      */
74341     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74342         if (ts.isDeclarationBindingElement(bindingElement)) {
74343             // `1` in `let { a = 1 } = ...`
74344             // `1` in `let { a: b = 1 } = ...`
74345             // `1` in `let { a: {b} = 1 } = ...`
74346             // `1` in `let { a: [b] = 1 } = ...`
74347             // `1` in `let [a = 1] = ...`
74348             // `1` in `let [{a} = 1] = ...`
74349             // `1` in `let [[a] = 1] = ...`
74350             return bindingElement.initializer;
74351         }
74352         if (ts.isPropertyAssignment(bindingElement)) {
74353             // `1` in `({ a: b = 1 } = ...)`
74354             // `1` in `({ a: {b} = 1 } = ...)`
74355             // `1` in `({ a: [b] = 1 } = ...)`
74356             var initializer = bindingElement.initializer;
74357             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74358                 ? initializer.right
74359                 : undefined;
74360         }
74361         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74362             // `1` in `({ a = 1 } = ...)`
74363             return bindingElement.objectAssignmentInitializer;
74364         }
74365         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74366             // `1` in `[a = 1] = ...`
74367             // `1` in `[{a} = 1] = ...`
74368             // `1` in `[[a] = 1] = ...`
74369             return bindingElement.right;
74370         }
74371         if (ts.isSpreadElement(bindingElement)) {
74372             // Recovery consistent with existing emit.
74373             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74374         }
74375     }
74376     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74377     /**
74378      * Gets the name of an BindingOrAssignmentElement.
74379      */
74380     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74381         if (ts.isDeclarationBindingElement(bindingElement)) {
74382             // `a` in `let { a } = ...`
74383             // `a` in `let { a = 1 } = ...`
74384             // `b` in `let { a: b } = ...`
74385             // `b` in `let { a: b = 1 } = ...`
74386             // `a` in `let { ...a } = ...`
74387             // `{b}` in `let { a: {b} } = ...`
74388             // `{b}` in `let { a: {b} = 1 } = ...`
74389             // `[b]` in `let { a: [b] } = ...`
74390             // `[b]` in `let { a: [b] = 1 } = ...`
74391             // `a` in `let [a] = ...`
74392             // `a` in `let [a = 1] = ...`
74393             // `a` in `let [...a] = ...`
74394             // `{a}` in `let [{a}] = ...`
74395             // `{a}` in `let [{a} = 1] = ...`
74396             // `[a]` in `let [[a]] = ...`
74397             // `[a]` in `let [[a] = 1] = ...`
74398             return bindingElement.name;
74399         }
74400         if (ts.isObjectLiteralElementLike(bindingElement)) {
74401             switch (bindingElement.kind) {
74402                 case 281 /* PropertyAssignment */:
74403                     // `b` in `({ a: b } = ...)`
74404                     // `b` in `({ a: b = 1 } = ...)`
74405                     // `{b}` in `({ a: {b} } = ...)`
74406                     // `{b}` in `({ a: {b} = 1 } = ...)`
74407                     // `[b]` in `({ a: [b] } = ...)`
74408                     // `[b]` in `({ a: [b] = 1 } = ...)`
74409                     // `b.c` in `({ a: b.c } = ...)`
74410                     // `b.c` in `({ a: b.c = 1 } = ...)`
74411                     // `b[0]` in `({ a: b[0] } = ...)`
74412                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74413                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74414                 case 282 /* ShorthandPropertyAssignment */:
74415                     // `a` in `({ a } = ...)`
74416                     // `a` in `({ a = 1 } = ...)`
74417                     return bindingElement.name;
74418                 case 283 /* SpreadAssignment */:
74419                     // `a` in `({ ...a } = ...)`
74420                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74421             }
74422             // no target
74423             return undefined;
74424         }
74425         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74426             // `a` in `[a = 1] = ...`
74427             // `{a}` in `[{a} = 1] = ...`
74428             // `[a]` in `[[a] = 1] = ...`
74429             // `a.b` in `[a.b = 1] = ...`
74430             // `a[0]` in `[a[0] = 1] = ...`
74431             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74432         }
74433         if (ts.isSpreadElement(bindingElement)) {
74434             // `a` in `[...a] = ...`
74435             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74436         }
74437         // `a` in `[a] = ...`
74438         // `{a}` in `[{a}] = ...`
74439         // `[a]` in `[[a]] = ...`
74440         // `a.b` in `[a.b] = ...`
74441         // `a[0]` in `[a[0]] = ...`
74442         return bindingElement;
74443     }
74444     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74445     /**
74446      * Determines whether an BindingOrAssignmentElement is a rest element.
74447      */
74448     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74449         switch (bindingElement.kind) {
74450             case 156 /* Parameter */:
74451             case 191 /* BindingElement */:
74452                 // `...` in `let [...a] = ...`
74453                 return bindingElement.dotDotDotToken;
74454             case 213 /* SpreadElement */:
74455             case 283 /* SpreadAssignment */:
74456                 // `...` in `[...a] = ...`
74457                 return bindingElement;
74458         }
74459         return undefined;
74460     }
74461     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74462     /**
74463      * Gets the property name of a BindingOrAssignmentElement
74464      */
74465     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74466         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74467         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74468         return propertyName;
74469     }
74470     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74471     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74472         switch (bindingElement.kind) {
74473             case 191 /* BindingElement */:
74474                 // `a` in `let { a: b } = ...`
74475                 // `[a]` in `let { [a]: b } = ...`
74476                 // `"a"` in `let { "a": b } = ...`
74477                 // `1` in `let { 1: b } = ...`
74478                 if (bindingElement.propertyName) {
74479                     var propertyName = bindingElement.propertyName;
74480                     if (ts.isPrivateIdentifier(propertyName)) {
74481                         return ts.Debug.failBadSyntaxKind(propertyName);
74482                     }
74483                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74484                         ? propertyName.expression
74485                         : propertyName;
74486                 }
74487                 break;
74488             case 281 /* PropertyAssignment */:
74489                 // `a` in `({ a: b } = ...)`
74490                 // `[a]` in `({ [a]: b } = ...)`
74491                 // `"a"` in `({ "a": b } = ...)`
74492                 // `1` in `({ 1: b } = ...)`
74493                 if (bindingElement.name) {
74494                     var propertyName = bindingElement.name;
74495                     if (ts.isPrivateIdentifier(propertyName)) {
74496                         return ts.Debug.failBadSyntaxKind(propertyName);
74497                     }
74498                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74499                         ? propertyName.expression
74500                         : propertyName;
74501                 }
74502                 break;
74503             case 283 /* SpreadAssignment */:
74504                 // `a` in `({ ...a } = ...)`
74505                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74506                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74507                 }
74508                 return bindingElement.name;
74509         }
74510         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74511         if (target && ts.isPropertyName(target)) {
74512             return target;
74513         }
74514     }
74515     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74516     function isStringOrNumericLiteral(node) {
74517         var kind = node.kind;
74518         return kind === 10 /* StringLiteral */
74519             || kind === 8 /* NumericLiteral */;
74520     }
74521     /**
74522      * Gets the elements of a BindingOrAssignmentPattern
74523      */
74524     function getElementsOfBindingOrAssignmentPattern(name) {
74525         switch (name.kind) {
74526             case 189 /* ObjectBindingPattern */:
74527             case 190 /* ArrayBindingPattern */:
74528             case 192 /* ArrayLiteralExpression */:
74529                 // `a` in `{a}`
74530                 // `a` in `[a]`
74531                 return name.elements;
74532             case 193 /* ObjectLiteralExpression */:
74533                 // `a` in `{a}`
74534                 return name.properties;
74535         }
74536     }
74537     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74538     function convertToArrayAssignmentElement(element) {
74539         if (ts.isBindingElement(element)) {
74540             if (element.dotDotDotToken) {
74541                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74542                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74543             }
74544             var expression = convertToAssignmentElementTarget(element.name);
74545             return element.initializer
74546                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74547                 : expression;
74548         }
74549         ts.Debug.assertNode(element, ts.isExpression);
74550         return element;
74551     }
74552     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74553     function convertToObjectAssignmentElement(element) {
74554         if (ts.isBindingElement(element)) {
74555             if (element.dotDotDotToken) {
74556                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74557                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74558             }
74559             if (element.propertyName) {
74560                 var expression = convertToAssignmentElementTarget(element.name);
74561                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74562             }
74563             ts.Debug.assertNode(element.name, ts.isIdentifier);
74564             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74565         }
74566         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74567         return element;
74568     }
74569     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74570     function convertToAssignmentPattern(node) {
74571         switch (node.kind) {
74572             case 190 /* ArrayBindingPattern */:
74573             case 192 /* ArrayLiteralExpression */:
74574                 return convertToArrayAssignmentPattern(node);
74575             case 189 /* ObjectBindingPattern */:
74576             case 193 /* ObjectLiteralExpression */:
74577                 return convertToObjectAssignmentPattern(node);
74578         }
74579     }
74580     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74581     function convertToObjectAssignmentPattern(node) {
74582         if (ts.isObjectBindingPattern(node)) {
74583             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74584         }
74585         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74586         return node;
74587     }
74588     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74589     function convertToArrayAssignmentPattern(node) {
74590         if (ts.isArrayBindingPattern(node)) {
74591             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74592         }
74593         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74594         return node;
74595     }
74596     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74597     function convertToAssignmentElementTarget(node) {
74598         if (ts.isBindingPattern(node)) {
74599             return convertToAssignmentPattern(node);
74600         }
74601         ts.Debug.assertNode(node, ts.isExpression);
74602         return node;
74603     }
74604     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74605 })(ts || (ts = {}));
74606 var ts;
74607 (function (ts) {
74608     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74609     function visitNode(node, visitor, test, lift) {
74610         if (node === undefined || visitor === undefined) {
74611             return node;
74612         }
74613         ts.aggregateTransformFlags(node);
74614         var visited = visitor(node);
74615         if (visited === node) {
74616             return node;
74617         }
74618         var visitedNode;
74619         if (visited === undefined) {
74620             return undefined;
74621         }
74622         else if (ts.isArray(visited)) {
74623             visitedNode = (lift || extractSingleNode)(visited);
74624         }
74625         else {
74626             visitedNode = visited;
74627         }
74628         ts.Debug.assertNode(visitedNode, test);
74629         ts.aggregateTransformFlags(visitedNode);
74630         return visitedNode;
74631     }
74632     ts.visitNode = visitNode;
74633     /**
74634      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74635      *
74636      * @param nodes The NodeArray to visit.
74637      * @param visitor The callback used to visit a Node.
74638      * @param test A node test to execute for each node.
74639      * @param start An optional value indicating the starting offset at which to start visiting.
74640      * @param count An optional value indicating the maximum number of nodes to visit.
74641      */
74642     function visitNodes(nodes, visitor, test, start, count) {
74643         if (nodes === undefined || visitor === undefined) {
74644             return nodes;
74645         }
74646         var updated;
74647         // Ensure start and count have valid values
74648         var length = nodes.length;
74649         if (start === undefined || start < 0) {
74650             start = 0;
74651         }
74652         if (count === undefined || count > length - start) {
74653             count = length - start;
74654         }
74655         if (start > 0 || count < length) {
74656             // If we are not visiting all of the original nodes, we must always create a new array.
74657             // Since this is a fragment of a node array, we do not copy over the previous location
74658             // and will only copy over `hasTrailingComma` if we are including the last element.
74659             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74660         }
74661         // Visit each original node.
74662         for (var i = 0; i < count; i++) {
74663             var node = nodes[i + start];
74664             ts.aggregateTransformFlags(node);
74665             var visited = node !== undefined ? visitor(node) : undefined;
74666             if (updated !== undefined || visited === undefined || visited !== node) {
74667                 if (updated === undefined) {
74668                     // Ensure we have a copy of `nodes`, up to the current index.
74669                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74670                     ts.setTextRange(updated, nodes);
74671                 }
74672                 if (visited) {
74673                     if (ts.isArray(visited)) {
74674                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74675                             var visitedNode = visited_1[_i];
74676                             ts.Debug.assertNode(visitedNode, test);
74677                             ts.aggregateTransformFlags(visitedNode);
74678                             updated.push(visitedNode);
74679                         }
74680                     }
74681                     else {
74682                         ts.Debug.assertNode(visited, test);
74683                         ts.aggregateTransformFlags(visited);
74684                         updated.push(visited);
74685                     }
74686                 }
74687             }
74688         }
74689         return updated || nodes;
74690     }
74691     ts.visitNodes = visitNodes;
74692     /**
74693      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74694      * and merging hoisted declarations upon completion.
74695      */
74696     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74697         context.startLexicalEnvironment();
74698         statements = visitNodes(statements, visitor, ts.isStatement, start);
74699         if (ensureUseStrict)
74700             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74701         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74702     }
74703     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74704     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74705         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74706         var updated;
74707         context.startLexicalEnvironment();
74708         if (nodes) {
74709             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74710             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74711             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74712             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74713             // that we might transform that introduces a temporary variable would fail as the temporary variable
74714             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74715             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74716             // when the emit target is greater than ES2015.
74717             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74718                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74719                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74720             }
74721             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74722         }
74723         context.suspendLexicalEnvironment();
74724         return updated;
74725     }
74726     ts.visitParameterList = visitParameterList;
74727     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74728         var result;
74729         for (var i = 0; i < parameters.length; i++) {
74730             var parameter = parameters[i];
74731             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74732             if (result || updated !== parameter) {
74733                 if (!result)
74734                     result = parameters.slice(0, i);
74735                 result[i] = updated;
74736             }
74737         }
74738         if (result) {
74739             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74740         }
74741         return parameters;
74742     }
74743     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74744         // A rest parameter cannot have a binding pattern or an initializer,
74745         // so let's just ignore it.
74746         return parameter.dotDotDotToken ? parameter :
74747             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74748                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74749                     parameter;
74750     }
74751     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74752         context.addInitializationStatement(ts.createVariableStatement(
74753         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74754             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74755                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74756                 ts.getGeneratedNameForNode(parameter)),
74757         ])));
74758         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74759         /*initializer*/ undefined);
74760     }
74761     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74762         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74763             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 */))
74764         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74765         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74766         /*initializer*/ undefined);
74767     }
74768     function visitFunctionBody(node, visitor, context) {
74769         context.resumeLexicalEnvironment();
74770         var updated = visitNode(node, visitor, ts.isConciseBody);
74771         var declarations = context.endLexicalEnvironment();
74772         if (ts.some(declarations)) {
74773             var block = ts.convertToFunctionBody(updated);
74774             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74775             return ts.updateBlock(block, statements);
74776         }
74777         return updated;
74778     }
74779     ts.visitFunctionBody = visitFunctionBody;
74780     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74781         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74782         if (node === undefined) {
74783             return undefined;
74784         }
74785         var kind = node.kind;
74786         // No need to visit nodes with no children.
74787         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74788             return node;
74789         }
74790         switch (kind) {
74791             // Names
74792             case 75 /* Identifier */:
74793                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74794             case 153 /* QualifiedName */:
74795                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74796             case 154 /* ComputedPropertyName */:
74797                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74798             // Signature elements
74799             case 155 /* TypeParameter */:
74800                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74801             case 156 /* Parameter */:
74802                 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));
74803             case 157 /* Decorator */:
74804                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74805             // Type elements
74806             case 158 /* PropertySignature */:
74807                 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));
74808             case 159 /* PropertyDeclaration */:
74809                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74810                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74811                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74812             case 160 /* MethodSignature */:
74813                 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));
74814             case 161 /* MethodDeclaration */:
74815                 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));
74816             case 162 /* Constructor */:
74817                 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));
74818             case 163 /* GetAccessor */:
74819                 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));
74820             case 164 /* SetAccessor */:
74821                 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));
74822             case 165 /* CallSignature */:
74823                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74824             case 166 /* ConstructSignature */:
74825                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74826             case 167 /* IndexSignature */:
74827                 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));
74828             // Types
74829             case 168 /* TypePredicate */:
74830                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
74831             case 169 /* TypeReference */:
74832                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
74833             case 170 /* FunctionType */:
74834                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74835             case 171 /* ConstructorType */:
74836                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74837             case 172 /* TypeQuery */:
74838                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
74839             case 173 /* TypeLiteral */:
74840                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
74841             case 174 /* ArrayType */:
74842                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
74843             case 175 /* TupleType */:
74844                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
74845             case 176 /* OptionalType */:
74846                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74847             case 177 /* RestType */:
74848                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74849             case 178 /* UnionType */:
74850                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74851             case 179 /* IntersectionType */:
74852                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74853             case 180 /* ConditionalType */:
74854                 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));
74855             case 181 /* InferType */:
74856                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
74857             case 188 /* ImportType */:
74858                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
74859             case 182 /* ParenthesizedType */:
74860                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
74861             case 184 /* TypeOperator */:
74862                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74863             case 185 /* IndexedAccessType */:
74864                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
74865             case 186 /* MappedType */:
74866                 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));
74867             case 187 /* LiteralType */:
74868                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
74869             // Binding patterns
74870             case 189 /* ObjectBindingPattern */:
74871                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
74872             case 190 /* ArrayBindingPattern */:
74873                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
74874             case 191 /* BindingElement */:
74875                 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));
74876             // Expression
74877             case 192 /* ArrayLiteralExpression */:
74878                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
74879             case 193 /* ObjectLiteralExpression */:
74880                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
74881             case 194 /* PropertyAccessExpression */:
74882                 if (node.flags & 32 /* OptionalChain */) {
74883                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
74884                 }
74885                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
74886             case 195 /* ElementAccessExpression */:
74887                 if (node.flags & 32 /* OptionalChain */) {
74888                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
74889                 }
74890                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
74891             case 196 /* CallExpression */:
74892                 if (node.flags & 32 /* OptionalChain */) {
74893                     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));
74894                 }
74895                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74896             case 197 /* NewExpression */:
74897                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74898             case 198 /* TaggedTemplateExpression */:
74899                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
74900             case 199 /* TypeAssertionExpression */:
74901                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74902             case 200 /* ParenthesizedExpression */:
74903                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
74904             case 201 /* FunctionExpression */:
74905                 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));
74906             case 202 /* ArrowFunction */:
74907                 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));
74908             case 203 /* DeleteExpression */:
74909                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
74910             case 204 /* TypeOfExpression */:
74911                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
74912             case 205 /* VoidExpression */:
74913                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
74914             case 206 /* AwaitExpression */:
74915                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
74916             case 207 /* PrefixUnaryExpression */:
74917                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
74918             case 208 /* PostfixUnaryExpression */:
74919                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
74920             case 209 /* BinaryExpression */:
74921                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
74922             case 210 /* ConditionalExpression */:
74923                 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));
74924             case 211 /* TemplateExpression */:
74925                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
74926             case 212 /* YieldExpression */:
74927                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
74928             case 213 /* SpreadElement */:
74929                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
74930             case 214 /* ClassExpression */:
74931                 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));
74932             case 216 /* ExpressionWithTypeArguments */:
74933                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74934             case 217 /* AsExpression */:
74935                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
74936             case 218 /* NonNullExpression */:
74937                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
74938             case 219 /* MetaProperty */:
74939                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
74940             // Misc
74941             case 221 /* TemplateSpan */:
74942                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
74943             // Element
74944             case 223 /* Block */:
74945                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74946             case 225 /* VariableStatement */:
74947                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
74948             case 226 /* ExpressionStatement */:
74949                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
74950             case 227 /* IfStatement */:
74951                 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));
74952             case 228 /* DoStatement */:
74953                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
74954             case 229 /* WhileStatement */:
74955                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74956             case 230 /* ForStatement */:
74957                 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));
74958             case 231 /* ForInStatement */:
74959                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74960             case 232 /* ForOfStatement */:
74961                 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));
74962             case 233 /* ContinueStatement */:
74963                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
74964             case 234 /* BreakStatement */:
74965                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
74966             case 235 /* ReturnStatement */:
74967                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
74968             case 236 /* WithStatement */:
74969                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74970             case 237 /* SwitchStatement */:
74971                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
74972             case 238 /* LabeledStatement */:
74973                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74974             case 239 /* ThrowStatement */:
74975                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
74976             case 240 /* TryStatement */:
74977                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
74978             case 242 /* VariableDeclaration */:
74979                 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));
74980             case 243 /* VariableDeclarationList */:
74981                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
74982             case 244 /* FunctionDeclaration */:
74983                 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));
74984             case 245 /* ClassDeclaration */:
74985                 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));
74986             case 246 /* InterfaceDeclaration */:
74987                 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));
74988             case 247 /* TypeAliasDeclaration */:
74989                 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));
74990             case 248 /* EnumDeclaration */:
74991                 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));
74992             case 249 /* ModuleDeclaration */:
74993                 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));
74994             case 250 /* ModuleBlock */:
74995                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74996             case 251 /* CaseBlock */:
74997                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
74998             case 252 /* NamespaceExportDeclaration */:
74999                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75000             case 253 /* ImportEqualsDeclaration */:
75001                 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));
75002             case 254 /* ImportDeclaration */:
75003                 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));
75004             case 255 /* ImportClause */:
75005                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75006             case 256 /* NamespaceImport */:
75007                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75008             case 262 /* NamespaceExport */:
75009                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75010             case 257 /* NamedImports */:
75011                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75012             case 258 /* ImportSpecifier */:
75013                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75014             case 259 /* ExportAssignment */:
75015                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75016             case 260 /* ExportDeclaration */:
75017                 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);
75018             case 261 /* NamedExports */:
75019                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75020             case 263 /* ExportSpecifier */:
75021                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75022             // Module references
75023             case 265 /* ExternalModuleReference */:
75024                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75025             // JSX
75026             case 266 /* JsxElement */:
75027                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75028             case 267 /* JsxSelfClosingElement */:
75029                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75030             case 268 /* JsxOpeningElement */:
75031                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75032             case 269 /* JsxClosingElement */:
75033                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75034             case 270 /* JsxFragment */:
75035                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75036             case 273 /* JsxAttribute */:
75037                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75038             case 274 /* JsxAttributes */:
75039                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75040             case 275 /* JsxSpreadAttribute */:
75041                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75042             case 276 /* JsxExpression */:
75043                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75044             // Clauses
75045             case 277 /* CaseClause */:
75046                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75047             case 278 /* DefaultClause */:
75048                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75049             case 279 /* HeritageClause */:
75050                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75051             case 280 /* CatchClause */:
75052                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75053             // Property assignments
75054             case 281 /* PropertyAssignment */:
75055                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75056             case 282 /* ShorthandPropertyAssignment */:
75057                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75058             case 283 /* SpreadAssignment */:
75059                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75060             // Enum
75061             case 284 /* EnumMember */:
75062                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75063             // Top-level nodes
75064             case 290 /* SourceFile */:
75065                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75066             // Transformation nodes
75067             case 326 /* PartiallyEmittedExpression */:
75068                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75069             case 327 /* CommaListExpression */:
75070                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75071             default:
75072                 // No need to visit nodes with no children.
75073                 return node;
75074         }
75075     }
75076     ts.visitEachChild = visitEachChild;
75077     /**
75078      * Extracts the single node from a NodeArray.
75079      *
75080      * @param nodes The NodeArray.
75081      */
75082     function extractSingleNode(nodes) {
75083         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75084         return ts.singleOrUndefined(nodes);
75085     }
75086 })(ts || (ts = {}));
75087 /* @internal */
75088 var ts;
75089 (function (ts) {
75090     function reduceNode(node, f, initial) {
75091         return node ? f(initial, node) : initial;
75092     }
75093     function reduceNodeArray(nodes, f, initial) {
75094         return nodes ? f(initial, nodes) : initial;
75095     }
75096     /**
75097      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75098      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75099      *
75100      * @param node The node containing the children to reduce.
75101      * @param initial The initial value to supply to the reduction.
75102      * @param f The callback function
75103      */
75104     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75105         if (node === undefined) {
75106             return initial;
75107         }
75108         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75109         var cbNodes = cbNodeArray || cbNode;
75110         var kind = node.kind;
75111         // No need to visit nodes with no children.
75112         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75113             return initial;
75114         }
75115         // We do not yet support types.
75116         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75117             return initial;
75118         }
75119         var result = initial;
75120         switch (node.kind) {
75121             // Leaf nodes
75122             case 222 /* SemicolonClassElement */:
75123             case 224 /* EmptyStatement */:
75124             case 215 /* OmittedExpression */:
75125             case 241 /* DebuggerStatement */:
75126             case 325 /* NotEmittedStatement */:
75127                 // No need to visit nodes with no children.
75128                 break;
75129             // Names
75130             case 153 /* QualifiedName */:
75131                 result = reduceNode(node.left, cbNode, result);
75132                 result = reduceNode(node.right, cbNode, result);
75133                 break;
75134             case 154 /* ComputedPropertyName */:
75135                 result = reduceNode(node.expression, cbNode, result);
75136                 break;
75137             // Signature elements
75138             case 156 /* Parameter */:
75139                 result = reduceNodes(node.decorators, cbNodes, result);
75140                 result = reduceNodes(node.modifiers, cbNodes, result);
75141                 result = reduceNode(node.name, cbNode, result);
75142                 result = reduceNode(node.type, cbNode, result);
75143                 result = reduceNode(node.initializer, cbNode, result);
75144                 break;
75145             case 157 /* Decorator */:
75146                 result = reduceNode(node.expression, cbNode, result);
75147                 break;
75148             // Type member
75149             case 158 /* PropertySignature */:
75150                 result = reduceNodes(node.modifiers, cbNodes, result);
75151                 result = reduceNode(node.name, cbNode, result);
75152                 result = reduceNode(node.questionToken, cbNode, result);
75153                 result = reduceNode(node.type, cbNode, result);
75154                 result = reduceNode(node.initializer, cbNode, result);
75155                 break;
75156             case 159 /* PropertyDeclaration */:
75157                 result = reduceNodes(node.decorators, cbNodes, result);
75158                 result = reduceNodes(node.modifiers, cbNodes, result);
75159                 result = reduceNode(node.name, cbNode, result);
75160                 result = reduceNode(node.type, cbNode, result);
75161                 result = reduceNode(node.initializer, cbNode, result);
75162                 break;
75163             case 161 /* MethodDeclaration */:
75164                 result = reduceNodes(node.decorators, cbNodes, result);
75165                 result = reduceNodes(node.modifiers, cbNodes, result);
75166                 result = reduceNode(node.name, cbNode, result);
75167                 result = reduceNodes(node.typeParameters, cbNodes, result);
75168                 result = reduceNodes(node.parameters, cbNodes, result);
75169                 result = reduceNode(node.type, cbNode, result);
75170                 result = reduceNode(node.body, cbNode, result);
75171                 break;
75172             case 162 /* Constructor */:
75173                 result = reduceNodes(node.modifiers, cbNodes, result);
75174                 result = reduceNodes(node.parameters, cbNodes, result);
75175                 result = reduceNode(node.body, cbNode, result);
75176                 break;
75177             case 163 /* GetAccessor */:
75178                 result = reduceNodes(node.decorators, cbNodes, result);
75179                 result = reduceNodes(node.modifiers, cbNodes, result);
75180                 result = reduceNode(node.name, cbNode, result);
75181                 result = reduceNodes(node.parameters, cbNodes, result);
75182                 result = reduceNode(node.type, cbNode, result);
75183                 result = reduceNode(node.body, cbNode, result);
75184                 break;
75185             case 164 /* SetAccessor */:
75186                 result = reduceNodes(node.decorators, cbNodes, result);
75187                 result = reduceNodes(node.modifiers, cbNodes, result);
75188                 result = reduceNode(node.name, cbNode, result);
75189                 result = reduceNodes(node.parameters, cbNodes, result);
75190                 result = reduceNode(node.body, cbNode, result);
75191                 break;
75192             // Binding patterns
75193             case 189 /* ObjectBindingPattern */:
75194             case 190 /* ArrayBindingPattern */:
75195                 result = reduceNodes(node.elements, cbNodes, result);
75196                 break;
75197             case 191 /* BindingElement */:
75198                 result = reduceNode(node.propertyName, cbNode, result);
75199                 result = reduceNode(node.name, cbNode, result);
75200                 result = reduceNode(node.initializer, cbNode, result);
75201                 break;
75202             // Expression
75203             case 192 /* ArrayLiteralExpression */:
75204                 result = reduceNodes(node.elements, cbNodes, result);
75205                 break;
75206             case 193 /* ObjectLiteralExpression */:
75207                 result = reduceNodes(node.properties, cbNodes, result);
75208                 break;
75209             case 194 /* PropertyAccessExpression */:
75210                 result = reduceNode(node.expression, cbNode, result);
75211                 result = reduceNode(node.name, cbNode, result);
75212                 break;
75213             case 195 /* ElementAccessExpression */:
75214                 result = reduceNode(node.expression, cbNode, result);
75215                 result = reduceNode(node.argumentExpression, cbNode, result);
75216                 break;
75217             case 196 /* CallExpression */:
75218                 result = reduceNode(node.expression, cbNode, result);
75219                 result = reduceNodes(node.typeArguments, cbNodes, result);
75220                 result = reduceNodes(node.arguments, cbNodes, result);
75221                 break;
75222             case 197 /* NewExpression */:
75223                 result = reduceNode(node.expression, cbNode, result);
75224                 result = reduceNodes(node.typeArguments, cbNodes, result);
75225                 result = reduceNodes(node.arguments, cbNodes, result);
75226                 break;
75227             case 198 /* TaggedTemplateExpression */:
75228                 result = reduceNode(node.tag, cbNode, result);
75229                 result = reduceNodes(node.typeArguments, cbNodes, result);
75230                 result = reduceNode(node.template, cbNode, result);
75231                 break;
75232             case 199 /* TypeAssertionExpression */:
75233                 result = reduceNode(node.type, cbNode, result);
75234                 result = reduceNode(node.expression, cbNode, result);
75235                 break;
75236             case 201 /* FunctionExpression */:
75237                 result = reduceNodes(node.modifiers, cbNodes, result);
75238                 result = reduceNode(node.name, cbNode, result);
75239                 result = reduceNodes(node.typeParameters, cbNodes, result);
75240                 result = reduceNodes(node.parameters, cbNodes, result);
75241                 result = reduceNode(node.type, cbNode, result);
75242                 result = reduceNode(node.body, cbNode, result);
75243                 break;
75244             case 202 /* ArrowFunction */:
75245                 result = reduceNodes(node.modifiers, cbNodes, result);
75246                 result = reduceNodes(node.typeParameters, cbNodes, result);
75247                 result = reduceNodes(node.parameters, cbNodes, result);
75248                 result = reduceNode(node.type, cbNode, result);
75249                 result = reduceNode(node.body, cbNode, result);
75250                 break;
75251             case 200 /* ParenthesizedExpression */:
75252             case 203 /* DeleteExpression */:
75253             case 204 /* TypeOfExpression */:
75254             case 205 /* VoidExpression */:
75255             case 206 /* AwaitExpression */:
75256             case 212 /* YieldExpression */:
75257             case 213 /* SpreadElement */:
75258             case 218 /* NonNullExpression */:
75259                 result = reduceNode(node.expression, cbNode, result);
75260                 break;
75261             case 207 /* PrefixUnaryExpression */:
75262             case 208 /* PostfixUnaryExpression */:
75263                 result = reduceNode(node.operand, cbNode, result);
75264                 break;
75265             case 209 /* BinaryExpression */:
75266                 result = reduceNode(node.left, cbNode, result);
75267                 result = reduceNode(node.right, cbNode, result);
75268                 break;
75269             case 210 /* ConditionalExpression */:
75270                 result = reduceNode(node.condition, cbNode, result);
75271                 result = reduceNode(node.whenTrue, cbNode, result);
75272                 result = reduceNode(node.whenFalse, cbNode, result);
75273                 break;
75274             case 211 /* TemplateExpression */:
75275                 result = reduceNode(node.head, cbNode, result);
75276                 result = reduceNodes(node.templateSpans, cbNodes, result);
75277                 break;
75278             case 214 /* ClassExpression */:
75279                 result = reduceNodes(node.modifiers, cbNodes, result);
75280                 result = reduceNode(node.name, cbNode, result);
75281                 result = reduceNodes(node.typeParameters, cbNodes, result);
75282                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75283                 result = reduceNodes(node.members, cbNodes, result);
75284                 break;
75285             case 216 /* ExpressionWithTypeArguments */:
75286                 result = reduceNode(node.expression, cbNode, result);
75287                 result = reduceNodes(node.typeArguments, cbNodes, result);
75288                 break;
75289             case 217 /* AsExpression */:
75290                 result = reduceNode(node.expression, cbNode, result);
75291                 result = reduceNode(node.type, cbNode, result);
75292                 break;
75293             // Misc
75294             case 221 /* TemplateSpan */:
75295                 result = reduceNode(node.expression, cbNode, result);
75296                 result = reduceNode(node.literal, cbNode, result);
75297                 break;
75298             // Element
75299             case 223 /* Block */:
75300                 result = reduceNodes(node.statements, cbNodes, result);
75301                 break;
75302             case 225 /* VariableStatement */:
75303                 result = reduceNodes(node.modifiers, cbNodes, result);
75304                 result = reduceNode(node.declarationList, cbNode, result);
75305                 break;
75306             case 226 /* ExpressionStatement */:
75307                 result = reduceNode(node.expression, cbNode, result);
75308                 break;
75309             case 227 /* IfStatement */:
75310                 result = reduceNode(node.expression, cbNode, result);
75311                 result = reduceNode(node.thenStatement, cbNode, result);
75312                 result = reduceNode(node.elseStatement, cbNode, result);
75313                 break;
75314             case 228 /* DoStatement */:
75315                 result = reduceNode(node.statement, cbNode, result);
75316                 result = reduceNode(node.expression, cbNode, result);
75317                 break;
75318             case 229 /* WhileStatement */:
75319             case 236 /* WithStatement */:
75320                 result = reduceNode(node.expression, cbNode, result);
75321                 result = reduceNode(node.statement, cbNode, result);
75322                 break;
75323             case 230 /* ForStatement */:
75324                 result = reduceNode(node.initializer, cbNode, result);
75325                 result = reduceNode(node.condition, cbNode, result);
75326                 result = reduceNode(node.incrementor, cbNode, result);
75327                 result = reduceNode(node.statement, cbNode, result);
75328                 break;
75329             case 231 /* ForInStatement */:
75330             case 232 /* ForOfStatement */:
75331                 result = reduceNode(node.initializer, cbNode, result);
75332                 result = reduceNode(node.expression, cbNode, result);
75333                 result = reduceNode(node.statement, cbNode, result);
75334                 break;
75335             case 235 /* ReturnStatement */:
75336             case 239 /* ThrowStatement */:
75337                 result = reduceNode(node.expression, cbNode, result);
75338                 break;
75339             case 237 /* SwitchStatement */:
75340                 result = reduceNode(node.expression, cbNode, result);
75341                 result = reduceNode(node.caseBlock, cbNode, result);
75342                 break;
75343             case 238 /* LabeledStatement */:
75344                 result = reduceNode(node.label, cbNode, result);
75345                 result = reduceNode(node.statement, cbNode, result);
75346                 break;
75347             case 240 /* TryStatement */:
75348                 result = reduceNode(node.tryBlock, cbNode, result);
75349                 result = reduceNode(node.catchClause, cbNode, result);
75350                 result = reduceNode(node.finallyBlock, cbNode, result);
75351                 break;
75352             case 242 /* VariableDeclaration */:
75353                 result = reduceNode(node.name, cbNode, result);
75354                 result = reduceNode(node.type, cbNode, result);
75355                 result = reduceNode(node.initializer, cbNode, result);
75356                 break;
75357             case 243 /* VariableDeclarationList */:
75358                 result = reduceNodes(node.declarations, cbNodes, result);
75359                 break;
75360             case 244 /* FunctionDeclaration */:
75361                 result = reduceNodes(node.decorators, cbNodes, result);
75362                 result = reduceNodes(node.modifiers, cbNodes, result);
75363                 result = reduceNode(node.name, cbNode, result);
75364                 result = reduceNodes(node.typeParameters, cbNodes, result);
75365                 result = reduceNodes(node.parameters, cbNodes, result);
75366                 result = reduceNode(node.type, cbNode, result);
75367                 result = reduceNode(node.body, cbNode, result);
75368                 break;
75369             case 245 /* ClassDeclaration */:
75370                 result = reduceNodes(node.decorators, cbNodes, result);
75371                 result = reduceNodes(node.modifiers, cbNodes, result);
75372                 result = reduceNode(node.name, cbNode, result);
75373                 result = reduceNodes(node.typeParameters, cbNodes, result);
75374                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75375                 result = reduceNodes(node.members, cbNodes, result);
75376                 break;
75377             case 248 /* EnumDeclaration */:
75378                 result = reduceNodes(node.decorators, cbNodes, result);
75379                 result = reduceNodes(node.modifiers, cbNodes, result);
75380                 result = reduceNode(node.name, cbNode, result);
75381                 result = reduceNodes(node.members, cbNodes, result);
75382                 break;
75383             case 249 /* ModuleDeclaration */:
75384                 result = reduceNodes(node.decorators, cbNodes, result);
75385                 result = reduceNodes(node.modifiers, cbNodes, result);
75386                 result = reduceNode(node.name, cbNode, result);
75387                 result = reduceNode(node.body, cbNode, result);
75388                 break;
75389             case 250 /* ModuleBlock */:
75390                 result = reduceNodes(node.statements, cbNodes, result);
75391                 break;
75392             case 251 /* CaseBlock */:
75393                 result = reduceNodes(node.clauses, cbNodes, result);
75394                 break;
75395             case 253 /* ImportEqualsDeclaration */:
75396                 result = reduceNodes(node.decorators, cbNodes, result);
75397                 result = reduceNodes(node.modifiers, cbNodes, result);
75398                 result = reduceNode(node.name, cbNode, result);
75399                 result = reduceNode(node.moduleReference, cbNode, result);
75400                 break;
75401             case 254 /* ImportDeclaration */:
75402                 result = reduceNodes(node.decorators, cbNodes, result);
75403                 result = reduceNodes(node.modifiers, cbNodes, result);
75404                 result = reduceNode(node.importClause, cbNode, result);
75405                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75406                 break;
75407             case 255 /* ImportClause */:
75408                 result = reduceNode(node.name, cbNode, result);
75409                 result = reduceNode(node.namedBindings, cbNode, result);
75410                 break;
75411             case 256 /* NamespaceImport */:
75412                 result = reduceNode(node.name, cbNode, result);
75413                 break;
75414             case 262 /* NamespaceExport */:
75415                 result = reduceNode(node.name, cbNode, result);
75416                 break;
75417             case 257 /* NamedImports */:
75418             case 261 /* NamedExports */:
75419                 result = reduceNodes(node.elements, cbNodes, result);
75420                 break;
75421             case 258 /* ImportSpecifier */:
75422             case 263 /* ExportSpecifier */:
75423                 result = reduceNode(node.propertyName, cbNode, result);
75424                 result = reduceNode(node.name, cbNode, result);
75425                 break;
75426             case 259 /* ExportAssignment */:
75427                 result = ts.reduceLeft(node.decorators, cbNode, result);
75428                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75429                 result = reduceNode(node.expression, cbNode, result);
75430                 break;
75431             case 260 /* ExportDeclaration */:
75432                 result = ts.reduceLeft(node.decorators, cbNode, result);
75433                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75434                 result = reduceNode(node.exportClause, cbNode, result);
75435                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75436                 break;
75437             // Module references
75438             case 265 /* ExternalModuleReference */:
75439                 result = reduceNode(node.expression, cbNode, result);
75440                 break;
75441             // JSX
75442             case 266 /* JsxElement */:
75443                 result = reduceNode(node.openingElement, cbNode, result);
75444                 result = ts.reduceLeft(node.children, cbNode, result);
75445                 result = reduceNode(node.closingElement, cbNode, result);
75446                 break;
75447             case 270 /* JsxFragment */:
75448                 result = reduceNode(node.openingFragment, cbNode, result);
75449                 result = ts.reduceLeft(node.children, cbNode, result);
75450                 result = reduceNode(node.closingFragment, cbNode, result);
75451                 break;
75452             case 267 /* JsxSelfClosingElement */:
75453             case 268 /* JsxOpeningElement */:
75454                 result = reduceNode(node.tagName, cbNode, result);
75455                 result = reduceNodes(node.typeArguments, cbNode, result);
75456                 result = reduceNode(node.attributes, cbNode, result);
75457                 break;
75458             case 274 /* JsxAttributes */:
75459                 result = reduceNodes(node.properties, cbNodes, result);
75460                 break;
75461             case 269 /* JsxClosingElement */:
75462                 result = reduceNode(node.tagName, cbNode, result);
75463                 break;
75464             case 273 /* JsxAttribute */:
75465                 result = reduceNode(node.name, cbNode, result);
75466                 result = reduceNode(node.initializer, cbNode, result);
75467                 break;
75468             case 275 /* JsxSpreadAttribute */:
75469                 result = reduceNode(node.expression, cbNode, result);
75470                 break;
75471             case 276 /* JsxExpression */:
75472                 result = reduceNode(node.expression, cbNode, result);
75473                 break;
75474             // Clauses
75475             case 277 /* CaseClause */:
75476                 result = reduceNode(node.expression, cbNode, result);
75477             // falls through
75478             case 278 /* DefaultClause */:
75479                 result = reduceNodes(node.statements, cbNodes, result);
75480                 break;
75481             case 279 /* HeritageClause */:
75482                 result = reduceNodes(node.types, cbNodes, result);
75483                 break;
75484             case 280 /* CatchClause */:
75485                 result = reduceNode(node.variableDeclaration, cbNode, result);
75486                 result = reduceNode(node.block, cbNode, result);
75487                 break;
75488             // Property assignments
75489             case 281 /* PropertyAssignment */:
75490                 result = reduceNode(node.name, cbNode, result);
75491                 result = reduceNode(node.initializer, cbNode, result);
75492                 break;
75493             case 282 /* ShorthandPropertyAssignment */:
75494                 result = reduceNode(node.name, cbNode, result);
75495                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75496                 break;
75497             case 283 /* SpreadAssignment */:
75498                 result = reduceNode(node.expression, cbNode, result);
75499                 break;
75500             // Enum
75501             case 284 /* EnumMember */:
75502                 result = reduceNode(node.name, cbNode, result);
75503                 result = reduceNode(node.initializer, cbNode, result);
75504                 break;
75505             // Top-level nodes
75506             case 290 /* SourceFile */:
75507                 result = reduceNodes(node.statements, cbNodes, result);
75508                 break;
75509             // Transformation nodes
75510             case 326 /* PartiallyEmittedExpression */:
75511                 result = reduceNode(node.expression, cbNode, result);
75512                 break;
75513             case 327 /* CommaListExpression */:
75514                 result = reduceNodes(node.elements, cbNodes, result);
75515                 break;
75516             default:
75517                 break;
75518         }
75519         return result;
75520     }
75521     ts.reduceEachChild = reduceEachChild;
75522     function findSpanEnd(array, test, start) {
75523         var i = start;
75524         while (i < array.length && test(array[i])) {
75525             i++;
75526         }
75527         return i;
75528     }
75529     function mergeLexicalEnvironment(statements, declarations) {
75530         if (!ts.some(declarations)) {
75531             return statements;
75532         }
75533         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75534         //
75535         // Given:
75536         //
75537         // | Left                               | Right                               |
75538         // |------------------------------------|-------------------------------------|
75539         // | [standard prologues (left)]        | [standard prologues (right)]        |
75540         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75541         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75542         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75543         // | [other statements (left)]          |                                     |
75544         //
75545         // The resulting statement list will be:
75546         //
75547         // | Result                              |
75548         // |-------------------------------------|
75549         // | [standard prologues (right)]        |
75550         // | [standard prologues (left)]         |
75551         // | [hoisted functions (right)]         |
75552         // | [hoisted functions (left)]          |
75553         // | [hoisted variables (right)]         |
75554         // | [hoisted variables (left)]          |
75555         // | [lexical init statements (right)]   |
75556         // | [lexical init statements (left)]    |
75557         // | [other statements (left)]           |
75558         //
75559         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75560         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75561         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75562         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75563         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75564         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75565         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75566         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75567         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75568         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75569         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75570         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75571         // splice prologues from the right into the left. We do this in reverse order
75572         // so that we don't need to recompute the index on the left when we insert items.
75573         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75574         // splice other custom prologues from right into left
75575         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75576             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75577         }
75578         // splice hoisted variables from right into left
75579         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75580             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75581         }
75582         // splice hoisted functions from right into left
75583         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75584             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75585         }
75586         // splice standard prologues from right into left (that are not already in left)
75587         if (rightStandardPrologueEnd > 0) {
75588             if (leftStandardPrologueEnd === 0) {
75589                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75590             }
75591             else {
75592                 var leftPrologues = ts.createMap();
75593                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75594                     var leftPrologue = statements[i];
75595                     leftPrologues.set(leftPrologue.expression.text, true);
75596                 }
75597                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75598                     var rightPrologue = declarations[i];
75599                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75600                         left.unshift(rightPrologue);
75601                     }
75602                 }
75603             }
75604         }
75605         if (ts.isNodeArray(statements)) {
75606             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75607         }
75608         return statements;
75609     }
75610     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75611     /**
75612      * Lifts a NodeArray containing only Statement nodes to a block.
75613      *
75614      * @param nodes The NodeArray.
75615      */
75616     function liftToBlock(nodes) {
75617         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75618         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75619     }
75620     ts.liftToBlock = liftToBlock;
75621     /**
75622      * Aggregates the TransformFlags for a Node and its subtree.
75623      */
75624     function aggregateTransformFlags(node) {
75625         aggregateTransformFlagsForNode(node);
75626         return node;
75627     }
75628     ts.aggregateTransformFlags = aggregateTransformFlags;
75629     /**
75630      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75631      * computed first, then the transform flags for the current node are computed from the subtree
75632      * flags and the state of the current node. Finally, the transform flags of the node are
75633      * returned, excluding any flags that should not be included in its parent node's subtree
75634      * flags.
75635      */
75636     function aggregateTransformFlagsForNode(node) {
75637         if (node === undefined) {
75638             return 0 /* None */;
75639         }
75640         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75641             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75642         }
75643         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75644         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75645     }
75646     function aggregateTransformFlagsForNodeArray(nodes) {
75647         if (nodes === undefined) {
75648             return 0 /* None */;
75649         }
75650         var subtreeFlags = 0 /* None */;
75651         var nodeArrayFlags = 0 /* None */;
75652         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75653             var node = nodes_3[_i];
75654             subtreeFlags |= aggregateTransformFlagsForNode(node);
75655             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75656         }
75657         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75658         return subtreeFlags;
75659     }
75660     /**
75661      * Aggregates the transform flags for the subtree of a node.
75662      */
75663     function aggregateTransformFlagsForSubtree(node) {
75664         // We do not transform ambient declarations or types, so there is no need to
75665         // recursively aggregate transform flags.
75666         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75667             return 0 /* None */;
75668         }
75669         // Aggregate the transform flags of each child.
75670         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75671     }
75672     /**
75673      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75674      * siblings.
75675      */
75676     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75677         return transformFlags | aggregateTransformFlagsForNode(node);
75678     }
75679     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75680         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75681     }
75682 })(ts || (ts = {}));
75683 /* @internal */
75684 var ts;
75685 (function (ts) {
75686     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75687         var _a = generatorOptions.extendedDiagnostics
75688             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75689             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75690         // Current source map file and its index in the sources list
75691         var rawSources = [];
75692         var sources = [];
75693         var sourceToSourceIndexMap = ts.createMap();
75694         var sourcesContent;
75695         var names = [];
75696         var nameToNameIndexMap;
75697         var mappings = "";
75698         // Last recorded and encoded mappings
75699         var lastGeneratedLine = 0;
75700         var lastGeneratedCharacter = 0;
75701         var lastSourceIndex = 0;
75702         var lastSourceLine = 0;
75703         var lastSourceCharacter = 0;
75704         var lastNameIndex = 0;
75705         var hasLast = false;
75706         var pendingGeneratedLine = 0;
75707         var pendingGeneratedCharacter = 0;
75708         var pendingSourceIndex = 0;
75709         var pendingSourceLine = 0;
75710         var pendingSourceCharacter = 0;
75711         var pendingNameIndex = 0;
75712         var hasPending = false;
75713         var hasPendingSource = false;
75714         var hasPendingName = false;
75715         return {
75716             getSources: function () { return rawSources; },
75717             addSource: addSource,
75718             setSourceContent: setSourceContent,
75719             addName: addName,
75720             addMapping: addMapping,
75721             appendSourceMap: appendSourceMap,
75722             toJSON: toJSON,
75723             toString: function () { return JSON.stringify(toJSON()); }
75724         };
75725         function addSource(fileName) {
75726             enter();
75727             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75728             /*isAbsolutePathAnUrl*/ true);
75729             var sourceIndex = sourceToSourceIndexMap.get(source);
75730             if (sourceIndex === undefined) {
75731                 sourceIndex = sources.length;
75732                 sources.push(source);
75733                 rawSources.push(fileName);
75734                 sourceToSourceIndexMap.set(source, sourceIndex);
75735             }
75736             exit();
75737             return sourceIndex;
75738         }
75739         /* eslint-disable boolean-trivia, no-null/no-null */
75740         function setSourceContent(sourceIndex, content) {
75741             enter();
75742             if (content !== null) {
75743                 if (!sourcesContent)
75744                     sourcesContent = [];
75745                 while (sourcesContent.length < sourceIndex) {
75746                     sourcesContent.push(null);
75747                 }
75748                 sourcesContent[sourceIndex] = content;
75749             }
75750             exit();
75751         }
75752         /* eslint-enable boolean-trivia, no-null/no-null */
75753         function addName(name) {
75754             enter();
75755             if (!nameToNameIndexMap)
75756                 nameToNameIndexMap = ts.createMap();
75757             var nameIndex = nameToNameIndexMap.get(name);
75758             if (nameIndex === undefined) {
75759                 nameIndex = names.length;
75760                 names.push(name);
75761                 nameToNameIndexMap.set(name, nameIndex);
75762             }
75763             exit();
75764             return nameIndex;
75765         }
75766         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75767             return !hasPending
75768                 || pendingGeneratedLine !== generatedLine
75769                 || pendingGeneratedCharacter !== generatedCharacter;
75770         }
75771         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75772             return sourceIndex !== undefined
75773                 && sourceLine !== undefined
75774                 && sourceCharacter !== undefined
75775                 && pendingSourceIndex === sourceIndex
75776                 && (pendingSourceLine > sourceLine
75777                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75778         }
75779         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75780             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75781             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75782             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75783             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75784             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75785             enter();
75786             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75787             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75788                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75789                 commitPendingMapping();
75790                 pendingGeneratedLine = generatedLine;
75791                 pendingGeneratedCharacter = generatedCharacter;
75792                 hasPendingSource = false;
75793                 hasPendingName = false;
75794                 hasPending = true;
75795             }
75796             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75797                 pendingSourceIndex = sourceIndex;
75798                 pendingSourceLine = sourceLine;
75799                 pendingSourceCharacter = sourceCharacter;
75800                 hasPendingSource = true;
75801                 if (nameIndex !== undefined) {
75802                     pendingNameIndex = nameIndex;
75803                     hasPendingName = true;
75804                 }
75805             }
75806             exit();
75807         }
75808         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75809             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75810             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75811             enter();
75812             // First, decode the old component sourcemap
75813             var sourceIndexToNewSourceIndexMap = [];
75814             var nameIndexToNewNameIndexMap;
75815             var mappingIterator = decodeMappings(map.mappings);
75816             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75817                 var raw = iterResult.value;
75818                 if (end && (raw.generatedLine > end.line ||
75819                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
75820                     break;
75821                 }
75822                 if (start && (raw.generatedLine < start.line ||
75823                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
75824                     continue;
75825                 }
75826                 // Then reencode all the updated mappings into the overall map
75827                 var newSourceIndex = void 0;
75828                 var newSourceLine = void 0;
75829                 var newSourceCharacter = void 0;
75830                 var newNameIndex = void 0;
75831                 if (raw.sourceIndex !== undefined) {
75832                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
75833                     if (newSourceIndex === undefined) {
75834                         // Apply offsets to each position and fixup source entries
75835                         var rawPath = map.sources[raw.sourceIndex];
75836                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
75837                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
75838                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
75839                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
75840                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
75841                         }
75842                     }
75843                     newSourceLine = raw.sourceLine;
75844                     newSourceCharacter = raw.sourceCharacter;
75845                     if (map.names && raw.nameIndex !== undefined) {
75846                         if (!nameIndexToNewNameIndexMap)
75847                             nameIndexToNewNameIndexMap = [];
75848                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
75849                         if (newNameIndex === undefined) {
75850                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
75851                         }
75852                     }
75853                 }
75854                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
75855                 var newGeneratedLine = rawGeneratedLine + generatedLine;
75856                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
75857                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
75858                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
75859             }
75860             exit();
75861         }
75862         function shouldCommitMapping() {
75863             return !hasLast
75864                 || lastGeneratedLine !== pendingGeneratedLine
75865                 || lastGeneratedCharacter !== pendingGeneratedCharacter
75866                 || lastSourceIndex !== pendingSourceIndex
75867                 || lastSourceLine !== pendingSourceLine
75868                 || lastSourceCharacter !== pendingSourceCharacter
75869                 || lastNameIndex !== pendingNameIndex;
75870         }
75871         function commitPendingMapping() {
75872             if (!hasPending || !shouldCommitMapping()) {
75873                 return;
75874             }
75875             enter();
75876             // Line/Comma delimiters
75877             if (lastGeneratedLine < pendingGeneratedLine) {
75878                 // Emit line delimiters
75879                 do {
75880                     mappings += ";";
75881                     lastGeneratedLine++;
75882                     lastGeneratedCharacter = 0;
75883                 } while (lastGeneratedLine < pendingGeneratedLine);
75884             }
75885             else {
75886                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
75887                 // Emit comma to separate the entry
75888                 if (hasLast) {
75889                     mappings += ",";
75890                 }
75891             }
75892             // 1. Relative generated character
75893             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
75894             lastGeneratedCharacter = pendingGeneratedCharacter;
75895             if (hasPendingSource) {
75896                 // 2. Relative sourceIndex
75897                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
75898                 lastSourceIndex = pendingSourceIndex;
75899                 // 3. Relative source line
75900                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
75901                 lastSourceLine = pendingSourceLine;
75902                 // 4. Relative source character
75903                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
75904                 lastSourceCharacter = pendingSourceCharacter;
75905                 if (hasPendingName) {
75906                     // 5. Relative nameIndex
75907                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
75908                     lastNameIndex = pendingNameIndex;
75909                 }
75910             }
75911             hasLast = true;
75912             exit();
75913         }
75914         function toJSON() {
75915             commitPendingMapping();
75916             return {
75917                 version: 3,
75918                 file: file,
75919                 sourceRoot: sourceRoot,
75920                 sources: sources,
75921                 names: names,
75922                 mappings: mappings,
75923                 sourcesContent: sourcesContent,
75924             };
75925         }
75926     }
75927     ts.createSourceMapGenerator = createSourceMapGenerator;
75928     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
75929     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
75930     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
75931     function getLineInfo(text, lineStarts) {
75932         return {
75933             getLineCount: function () { return lineStarts.length; },
75934             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
75935         };
75936     }
75937     ts.getLineInfo = getLineInfo;
75938     /**
75939      * Tries to find the sourceMappingURL comment at the end of a file.
75940      */
75941     function tryGetSourceMappingURL(lineInfo) {
75942         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
75943             var line = lineInfo.getLineText(index);
75944             var comment = sourceMapCommentRegExp.exec(line);
75945             if (comment) {
75946                 return comment[1];
75947             }
75948             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
75949             else if (!line.match(whitespaceOrMapCommentRegExp)) {
75950                 break;
75951             }
75952         }
75953     }
75954     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
75955     /* eslint-disable no-null/no-null */
75956     function isStringOrNull(x) {
75957         return typeof x === "string" || x === null;
75958     }
75959     function isRawSourceMap(x) {
75960         return x !== null
75961             && typeof x === "object"
75962             && x.version === 3
75963             && typeof x.file === "string"
75964             && typeof x.mappings === "string"
75965             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
75966             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
75967             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
75968             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
75969     }
75970     ts.isRawSourceMap = isRawSourceMap;
75971     /* eslint-enable no-null/no-null */
75972     function tryParseRawSourceMap(text) {
75973         try {
75974             var parsed = JSON.parse(text);
75975             if (isRawSourceMap(parsed)) {
75976                 return parsed;
75977             }
75978         }
75979         catch (_a) {
75980             // empty
75981         }
75982         return undefined;
75983     }
75984     ts.tryParseRawSourceMap = tryParseRawSourceMap;
75985     function decodeMappings(mappings) {
75986         var done = false;
75987         var pos = 0;
75988         var generatedLine = 0;
75989         var generatedCharacter = 0;
75990         var sourceIndex = 0;
75991         var sourceLine = 0;
75992         var sourceCharacter = 0;
75993         var nameIndex = 0;
75994         var error;
75995         return {
75996             get pos() { return pos; },
75997             get error() { return error; },
75998             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
75999             next: function () {
76000                 while (!done && pos < mappings.length) {
76001                     var ch = mappings.charCodeAt(pos);
76002                     if (ch === 59 /* semicolon */) {
76003                         // new line
76004                         generatedLine++;
76005                         generatedCharacter = 0;
76006                         pos++;
76007                         continue;
76008                     }
76009                     if (ch === 44 /* comma */) {
76010                         // Next entry is on same line - no action needed
76011                         pos++;
76012                         continue;
76013                     }
76014                     var hasSource = false;
76015                     var hasName = false;
76016                     generatedCharacter += base64VLQFormatDecode();
76017                     if (hasReportedError())
76018                         return stopIterating();
76019                     if (generatedCharacter < 0)
76020                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76021                     if (!isSourceMappingSegmentEnd()) {
76022                         hasSource = true;
76023                         sourceIndex += base64VLQFormatDecode();
76024                         if (hasReportedError())
76025                             return stopIterating();
76026                         if (sourceIndex < 0)
76027                             return setErrorAndStopIterating("Invalid sourceIndex found");
76028                         if (isSourceMappingSegmentEnd())
76029                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76030                         sourceLine += base64VLQFormatDecode();
76031                         if (hasReportedError())
76032                             return stopIterating();
76033                         if (sourceLine < 0)
76034                             return setErrorAndStopIterating("Invalid sourceLine found");
76035                         if (isSourceMappingSegmentEnd())
76036                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76037                         sourceCharacter += base64VLQFormatDecode();
76038                         if (hasReportedError())
76039                             return stopIterating();
76040                         if (sourceCharacter < 0)
76041                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76042                         if (!isSourceMappingSegmentEnd()) {
76043                             hasName = true;
76044                             nameIndex += base64VLQFormatDecode();
76045                             if (hasReportedError())
76046                                 return stopIterating();
76047                             if (nameIndex < 0)
76048                                 return setErrorAndStopIterating("Invalid nameIndex found");
76049                             if (!isSourceMappingSegmentEnd())
76050                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76051                         }
76052                     }
76053                     return { value: captureMapping(hasSource, hasName), done: done };
76054                 }
76055                 return stopIterating();
76056             }
76057         };
76058         function captureMapping(hasSource, hasName) {
76059             return {
76060                 generatedLine: generatedLine,
76061                 generatedCharacter: generatedCharacter,
76062                 sourceIndex: hasSource ? sourceIndex : undefined,
76063                 sourceLine: hasSource ? sourceLine : undefined,
76064                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76065                 nameIndex: hasName ? nameIndex : undefined
76066             };
76067         }
76068         function stopIterating() {
76069             done = true;
76070             return { value: undefined, done: true };
76071         }
76072         function setError(message) {
76073             if (error === undefined) {
76074                 error = message;
76075             }
76076         }
76077         function setErrorAndStopIterating(message) {
76078             setError(message);
76079             return stopIterating();
76080         }
76081         function hasReportedError() {
76082             return error !== undefined;
76083         }
76084         function isSourceMappingSegmentEnd() {
76085             return (pos === mappings.length ||
76086                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76087                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76088         }
76089         function base64VLQFormatDecode() {
76090             var moreDigits = true;
76091             var shiftCount = 0;
76092             var value = 0;
76093             for (; moreDigits; pos++) {
76094                 if (pos >= mappings.length)
76095                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76096                 // 6 digit number
76097                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76098                 if (currentByte === -1)
76099                     return setError("Invalid character in VLQ"), -1;
76100                 // If msb is set, we still have more bits to continue
76101                 moreDigits = (currentByte & 32) !== 0;
76102                 // least significant 5 bits are the next msbs in the final value.
76103                 value = value | ((currentByte & 31) << shiftCount);
76104                 shiftCount += 5;
76105             }
76106             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76107             if ((value & 1) === 0) {
76108                 // + number
76109                 value = value >> 1;
76110             }
76111             else {
76112                 // - number
76113                 value = value >> 1;
76114                 value = -value;
76115             }
76116             return value;
76117         }
76118     }
76119     ts.decodeMappings = decodeMappings;
76120     function sameMapping(left, right) {
76121         return left === right
76122             || left.generatedLine === right.generatedLine
76123                 && left.generatedCharacter === right.generatedCharacter
76124                 && left.sourceIndex === right.sourceIndex
76125                 && left.sourceLine === right.sourceLine
76126                 && left.sourceCharacter === right.sourceCharacter
76127                 && left.nameIndex === right.nameIndex;
76128     }
76129     ts.sameMapping = sameMapping;
76130     function isSourceMapping(mapping) {
76131         return mapping.sourceIndex !== undefined
76132             && mapping.sourceLine !== undefined
76133             && mapping.sourceCharacter !== undefined;
76134     }
76135     ts.isSourceMapping = isSourceMapping;
76136     function base64FormatEncode(value) {
76137         return value >= 0 && value < 26 ? 65 /* A */ + value :
76138             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76139                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76140                     value === 62 ? 43 /* plus */ :
76141                         value === 63 ? 47 /* slash */ :
76142                             ts.Debug.fail(value + ": not a base64 value");
76143     }
76144     function base64FormatDecode(ch) {
76145         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76146             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76147                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76148                     ch === 43 /* plus */ ? 62 :
76149                         ch === 47 /* slash */ ? 63 :
76150                             -1;
76151     }
76152     function base64VLQFormatEncode(inValue) {
76153         // Add a new least significant bit that has the sign of the value.
76154         // if negative number the least significant bit that gets added to the number has value 1
76155         // else least significant bit value that gets added is 0
76156         // eg. -1 changes to binary : 01 [1] => 3
76157         //     +1 changes to binary : 01 [0] => 2
76158         if (inValue < 0) {
76159             inValue = ((-inValue) << 1) + 1;
76160         }
76161         else {
76162             inValue = inValue << 1;
76163         }
76164         // Encode 5 bits at a time starting from least significant bits
76165         var encodedStr = "";
76166         do {
76167             var currentDigit = inValue & 31; // 11111
76168             inValue = inValue >> 5;
76169             if (inValue > 0) {
76170                 // There are still more digits to decode, set the msb (6th bit)
76171                 currentDigit = currentDigit | 32;
76172             }
76173             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76174         } while (inValue > 0);
76175         return encodedStr;
76176     }
76177     function isSourceMappedPosition(value) {
76178         return value.sourceIndex !== undefined
76179             && value.sourcePosition !== undefined;
76180     }
76181     function sameMappedPosition(left, right) {
76182         return left.generatedPosition === right.generatedPosition
76183             && left.sourceIndex === right.sourceIndex
76184             && left.sourcePosition === right.sourcePosition;
76185     }
76186     function compareSourcePositions(left, right) {
76187         // Compares sourcePosition without comparing sourceIndex
76188         // since the mappings are grouped by sourceIndex
76189         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76190         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76191     }
76192     function compareGeneratedPositions(left, right) {
76193         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76194     }
76195     function getSourcePositionOfMapping(value) {
76196         return value.sourcePosition;
76197     }
76198     function getGeneratedPositionOfMapping(value) {
76199         return value.generatedPosition;
76200     }
76201     function createDocumentPositionMapper(host, map, mapPath) {
76202         var mapDirectory = ts.getDirectoryPath(mapPath);
76203         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76204         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76205         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76206         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76207         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76208         var decodedMappings;
76209         var generatedMappings;
76210         var sourceMappings;
76211         return {
76212             getSourcePosition: getSourcePosition,
76213             getGeneratedPosition: getGeneratedPosition
76214         };
76215         function processMapping(mapping) {
76216             var generatedPosition = generatedFile !== undefined
76217                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76218                 : -1;
76219             var source;
76220             var sourcePosition;
76221             if (isSourceMapping(mapping)) {
76222                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76223                 source = map.sources[mapping.sourceIndex];
76224                 sourcePosition = sourceFile !== undefined
76225                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76226                     : -1;
76227             }
76228             return {
76229                 generatedPosition: generatedPosition,
76230                 source: source,
76231                 sourceIndex: mapping.sourceIndex,
76232                 sourcePosition: sourcePosition,
76233                 nameIndex: mapping.nameIndex
76234             };
76235         }
76236         function getDecodedMappings() {
76237             if (decodedMappings === undefined) {
76238                 var decoder = decodeMappings(map.mappings);
76239                 var mappings = ts.arrayFrom(decoder, processMapping);
76240                 if (decoder.error !== undefined) {
76241                     if (host.log) {
76242                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76243                     }
76244                     decodedMappings = ts.emptyArray;
76245                 }
76246                 else {
76247                     decodedMappings = mappings;
76248                 }
76249             }
76250             return decodedMappings;
76251         }
76252         function getSourceMappings(sourceIndex) {
76253             if (sourceMappings === undefined) {
76254                 var lists = [];
76255                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76256                     var mapping = _a[_i];
76257                     if (!isSourceMappedPosition(mapping))
76258                         continue;
76259                     var list = lists[mapping.sourceIndex];
76260                     if (!list)
76261                         lists[mapping.sourceIndex] = list = [];
76262                     list.push(mapping);
76263                 }
76264                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76265             }
76266             return sourceMappings[sourceIndex];
76267         }
76268         function getGeneratedMappings() {
76269             if (generatedMappings === undefined) {
76270                 var list = [];
76271                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76272                     var mapping = _a[_i];
76273                     list.push(mapping);
76274                 }
76275                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76276             }
76277             return generatedMappings;
76278         }
76279         function getGeneratedPosition(loc) {
76280             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76281             if (sourceIndex === undefined)
76282                 return loc;
76283             var sourceMappings = getSourceMappings(sourceIndex);
76284             if (!ts.some(sourceMappings))
76285                 return loc;
76286             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76287             if (targetIndex < 0) {
76288                 // if no exact match, closest is 2's complement of result
76289                 targetIndex = ~targetIndex;
76290             }
76291             var mapping = sourceMappings[targetIndex];
76292             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76293                 return loc;
76294             }
76295             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76296         }
76297         function getSourcePosition(loc) {
76298             var generatedMappings = getGeneratedMappings();
76299             if (!ts.some(generatedMappings))
76300                 return loc;
76301             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76302             if (targetIndex < 0) {
76303                 // if no exact match, closest is 2's complement of result
76304                 targetIndex = ~targetIndex;
76305             }
76306             var mapping = generatedMappings[targetIndex];
76307             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76308                 return loc;
76309             }
76310             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76311         }
76312     }
76313     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76314     ts.identitySourceMapConsumer = {
76315         getSourcePosition: ts.identity,
76316         getGeneratedPosition: ts.identity
76317     };
76318 })(ts || (ts = {}));
76319 /* @internal */
76320 var ts;
76321 (function (ts) {
76322     function getOriginalNodeId(node) {
76323         node = ts.getOriginalNode(node);
76324         return node ? ts.getNodeId(node) : 0;
76325     }
76326     ts.getOriginalNodeId = getOriginalNodeId;
76327     function containsDefaultReference(node) {
76328         if (!node)
76329             return false;
76330         if (!ts.isNamedImports(node))
76331             return false;
76332         return ts.some(node.elements, isNamedDefaultReference);
76333     }
76334     function isNamedDefaultReference(e) {
76335         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76336     }
76337     function chainBundle(transformSourceFile) {
76338         return transformSourceFileOrBundle;
76339         function transformSourceFileOrBundle(node) {
76340             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76341         }
76342         function transformBundle(node) {
76343             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76344         }
76345     }
76346     ts.chainBundle = chainBundle;
76347     function getExportNeedsImportStarHelper(node) {
76348         return !!ts.getNamespaceDeclarationNode(node);
76349     }
76350     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76351     function getImportNeedsImportStarHelper(node) {
76352         if (!!ts.getNamespaceDeclarationNode(node)) {
76353             return true;
76354         }
76355         var bindings = node.importClause && node.importClause.namedBindings;
76356         if (!bindings) {
76357             return false;
76358         }
76359         if (!ts.isNamedImports(bindings))
76360             return false;
76361         var defaultRefCount = 0;
76362         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76363             var binding = _a[_i];
76364             if (isNamedDefaultReference(binding)) {
76365                 defaultRefCount++;
76366             }
76367         }
76368         // 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
76369         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76370     }
76371     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76372     function getImportNeedsImportDefaultHelper(node) {
76373         // 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)
76374         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76375     }
76376     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76377     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76378         var externalImports = [];
76379         var exportSpecifiers = ts.createMultiMap();
76380         var exportedBindings = [];
76381         var uniqueExports = ts.createMap();
76382         var exportedNames;
76383         var hasExportDefault = false;
76384         var exportEquals;
76385         var hasExportStarsToExportValues = false;
76386         var hasImportStar = false;
76387         var hasImportDefault = false;
76388         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76389             var node = _a[_i];
76390             switch (node.kind) {
76391                 case 254 /* ImportDeclaration */:
76392                     // import "mod"
76393                     // import x from "mod"
76394                     // import * as x from "mod"
76395                     // import { x, y } from "mod"
76396                     externalImports.push(node);
76397                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76398                         hasImportStar = true;
76399                     }
76400                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76401                         hasImportDefault = true;
76402                     }
76403                     break;
76404                 case 253 /* ImportEqualsDeclaration */:
76405                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76406                         // import x = require("mod")
76407                         externalImports.push(node);
76408                     }
76409                     break;
76410                 case 260 /* ExportDeclaration */:
76411                     if (node.moduleSpecifier) {
76412                         if (!node.exportClause) {
76413                             // export * from "mod"
76414                             externalImports.push(node);
76415                             hasExportStarsToExportValues = true;
76416                         }
76417                         else {
76418                             // export * as ns from "mod"
76419                             // export { x, y } from "mod"
76420                             externalImports.push(node);
76421                         }
76422                     }
76423                     else {
76424                         // export { x, y }
76425                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76426                             var specifier = _c[_b];
76427                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76428                                 var name = specifier.propertyName || specifier.name;
76429                                 exportSpecifiers.add(ts.idText(name), specifier);
76430                                 var decl = resolver.getReferencedImportDeclaration(name)
76431                                     || resolver.getReferencedValueDeclaration(name);
76432                                 if (decl) {
76433                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76434                                 }
76435                                 uniqueExports.set(ts.idText(specifier.name), true);
76436                                 exportedNames = ts.append(exportedNames, specifier.name);
76437                             }
76438                         }
76439                     }
76440                     break;
76441                 case 259 /* ExportAssignment */:
76442                     if (node.isExportEquals && !exportEquals) {
76443                         // export = x
76444                         exportEquals = node;
76445                     }
76446                     break;
76447                 case 225 /* VariableStatement */:
76448                     if (ts.hasModifier(node, 1 /* Export */)) {
76449                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76450                             var decl = _e[_d];
76451                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76452                         }
76453                     }
76454                     break;
76455                 case 244 /* FunctionDeclaration */:
76456                     if (ts.hasModifier(node, 1 /* Export */)) {
76457                         if (ts.hasModifier(node, 512 /* Default */)) {
76458                             // export default function() { }
76459                             if (!hasExportDefault) {
76460                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76461                                 hasExportDefault = true;
76462                             }
76463                         }
76464                         else {
76465                             // export function x() { }
76466                             var name = node.name;
76467                             if (!uniqueExports.get(ts.idText(name))) {
76468                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76469                                 uniqueExports.set(ts.idText(name), true);
76470                                 exportedNames = ts.append(exportedNames, name);
76471                             }
76472                         }
76473                     }
76474                     break;
76475                 case 245 /* ClassDeclaration */:
76476                     if (ts.hasModifier(node, 1 /* Export */)) {
76477                         if (ts.hasModifier(node, 512 /* Default */)) {
76478                             // export default class { }
76479                             if (!hasExportDefault) {
76480                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76481                                 hasExportDefault = true;
76482                             }
76483                         }
76484                         else {
76485                             // export class x { }
76486                             var name = node.name;
76487                             if (name && !uniqueExports.get(ts.idText(name))) {
76488                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76489                                 uniqueExports.set(ts.idText(name), true);
76490                                 exportedNames = ts.append(exportedNames, name);
76491                             }
76492                         }
76493                     }
76494                     break;
76495             }
76496         }
76497         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76498         if (externalHelpersImportDeclaration) {
76499             externalImports.unshift(externalHelpersImportDeclaration);
76500         }
76501         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76502     }
76503     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76504     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76505         if (ts.isBindingPattern(decl.name)) {
76506             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76507                 var element = _a[_i];
76508                 if (!ts.isOmittedExpression(element)) {
76509                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76510                 }
76511             }
76512         }
76513         else if (!ts.isGeneratedIdentifier(decl.name)) {
76514             var text = ts.idText(decl.name);
76515             if (!uniqueExports.get(text)) {
76516                 uniqueExports.set(text, true);
76517                 exportedNames = ts.append(exportedNames, decl.name);
76518             }
76519         }
76520         return exportedNames;
76521     }
76522     /** Use a sparse array as a multi-map. */
76523     function multiMapSparseArrayAdd(map, key, value) {
76524         var values = map[key];
76525         if (values) {
76526             values.push(value);
76527         }
76528         else {
76529             map[key] = values = [value];
76530         }
76531         return values;
76532     }
76533     /**
76534      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76535      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76536      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76537      */
76538     function isSimpleCopiableExpression(expression) {
76539         return ts.isStringLiteralLike(expression) ||
76540             expression.kind === 8 /* NumericLiteral */ ||
76541             ts.isKeyword(expression.kind) ||
76542             ts.isIdentifier(expression);
76543     }
76544     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76545     /**
76546      * A simple inlinable expression is an expression which can be copied into multiple locations
76547      * without risk of repeating any sideeffects and whose value could not possibly change between
76548      * any such locations
76549      */
76550     function isSimpleInlineableExpression(expression) {
76551         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76552             ts.isWellKnownSymbolSyntactically(expression);
76553     }
76554     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76555     function isCompoundAssignment(kind) {
76556         return kind >= 63 /* FirstCompoundAssignment */
76557             && kind <= 74 /* LastCompoundAssignment */;
76558     }
76559     ts.isCompoundAssignment = isCompoundAssignment;
76560     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76561         switch (kind) {
76562             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76563             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76564             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76565             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76566             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76567             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76568             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76569             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76570             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76571             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76572             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76573             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76574         }
76575     }
76576     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76577     /**
76578      * Adds super call and preceding prologue directives into the list of statements.
76579      *
76580      * @param ctor The constructor node.
76581      * @param result The list of statements.
76582      * @param visitor The visitor to apply to each node added to the result array.
76583      * @returns index of the statement that follows super call
76584      */
76585     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76586         if (ctor.body) {
76587             var statements = ctor.body.statements;
76588             // add prologue directives to the list (if any)
76589             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76590             if (index === statements.length) {
76591                 // list contains nothing but prologue directives (or empty) - exit
76592                 return index;
76593             }
76594             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76595             if (superIndex > -1) {
76596                 for (var i = index; i <= superIndex; i++) {
76597                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76598                 }
76599                 return superIndex + 1;
76600             }
76601             return index;
76602         }
76603         return 0;
76604     }
76605     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76606     /**
76607      * @param input Template string input strings
76608      * @param args Names which need to be made file-level unique
76609      */
76610     function helperString(input) {
76611         var args = [];
76612         for (var _i = 1; _i < arguments.length; _i++) {
76613             args[_i - 1] = arguments[_i];
76614         }
76615         return function (uniqueName) {
76616             var result = "";
76617             for (var i = 0; i < args.length; i++) {
76618                 result += input[i];
76619                 result += uniqueName(args[i]);
76620             }
76621             result += input[input.length - 1];
76622             return result;
76623         };
76624     }
76625     ts.helperString = helperString;
76626     /**
76627      * Gets all the static or all the instance property declarations of a class
76628      *
76629      * @param node The class node.
76630      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76631      */
76632     function getProperties(node, requireInitializer, isStatic) {
76633         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76634     }
76635     ts.getProperties = getProperties;
76636     /**
76637      * Is a class element either a static or an instance property declaration with an initializer?
76638      *
76639      * @param member The class element node.
76640      * @param isStatic A value indicating whether the member should be a static or instance member.
76641      */
76642     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76643         return ts.isPropertyDeclaration(member)
76644             && (!!member.initializer || !requireInitializer)
76645             && ts.hasStaticModifier(member) === isStatic;
76646     }
76647     /**
76648      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76649      *
76650      * @param member The class element node.
76651      * @param isStatic A value indicating whether the member should be a static or instance member.
76652      */
76653     function isInitializedProperty(member) {
76654         return member.kind === 159 /* PropertyDeclaration */
76655             && member.initializer !== undefined;
76656     }
76657     ts.isInitializedProperty = isInitializedProperty;
76658 })(ts || (ts = {}));
76659 /*@internal*/
76660 var ts;
76661 (function (ts) {
76662     var FlattenLevel;
76663     (function (FlattenLevel) {
76664         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76665         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76666     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76667     /**
76668      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76669      *
76670      * @param node The node to flatten.
76671      * @param visitor An optional visitor used to visit initializers.
76672      * @param context The transformation context.
76673      * @param level Indicates the extent to which flattening should occur.
76674      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76675      * the destructuring assignment is needed as part of a larger expression.
76676      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76677      */
76678     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76679         var location = node;
76680         var value;
76681         if (ts.isDestructuringAssignment(node)) {
76682             value = node.right;
76683             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76684                 if (ts.isDestructuringAssignment(value)) {
76685                     location = node = value;
76686                     value = node.right;
76687                 }
76688                 else {
76689                     return ts.visitNode(value, visitor, ts.isExpression);
76690                 }
76691             }
76692         }
76693         var expressions;
76694         var flattenContext = {
76695             context: context,
76696             level: level,
76697             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76698             hoistTempVariables: true,
76699             emitExpression: emitExpression,
76700             emitBindingOrAssignment: emitBindingOrAssignment,
76701             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76702             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76703             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76704             visitor: visitor
76705         };
76706         if (value) {
76707             value = ts.visitNode(value, visitor, ts.isExpression);
76708             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76709                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76710                 // If the right-hand value of the assignment is also an assignment target then
76711                 // we need to cache the right-hand value.
76712                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76713             }
76714             else if (needsValue) {
76715                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76716                 // is the case when the destructuring assignment is part of a larger expression),
76717                 // then we need to cache the right-hand value.
76718                 //
76719                 // The source map location for the assignment should point to the entire binary
76720                 // expression.
76721                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76722             }
76723             else if (ts.nodeIsSynthesized(node)) {
76724                 // Generally, the source map location for a destructuring assignment is the root
76725                 // expression.
76726                 //
76727                 // However, if the root expression is synthesized (as in the case
76728                 // of the initializer when transforming a ForOfStatement), then the source map
76729                 // location should point to the right-hand value of the expression.
76730                 location = value;
76731             }
76732         }
76733         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76734         if (value && needsValue) {
76735             if (!ts.some(expressions)) {
76736                 return value;
76737             }
76738             expressions.push(value);
76739         }
76740         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76741         function emitExpression(expression) {
76742             ts.aggregateTransformFlags(expression);
76743             expressions = ts.append(expressions, expression);
76744         }
76745         function emitBindingOrAssignment(target, value, location, original) {
76746             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76747             var expression = createAssignmentCallback
76748                 ? createAssignmentCallback(target, value, location)
76749                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76750             expression.original = original;
76751             emitExpression(expression);
76752         }
76753     }
76754     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76755     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76756         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76757         if (ts.isBindingOrAssignmentPattern(target)) {
76758             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76759         }
76760         else if (ts.isIdentifier(target)) {
76761             return target.escapedText === escapedName;
76762         }
76763         return false;
76764     }
76765     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76766         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76767         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76768             var element = elements_3[_i];
76769             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76770                 return true;
76771             }
76772         }
76773         return false;
76774     }
76775     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76776         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76777         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76778             return true;
76779         }
76780         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76781         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76782     }
76783     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76784         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76785     }
76786     /**
76787      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76788      *
76789      * @param node The node to flatten.
76790      * @param visitor An optional visitor used to visit initializers.
76791      * @param context The transformation context.
76792      * @param boundValue The value bound to the declaration.
76793      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76794      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76795      * @param level Indicates the extent to which flattening should occur.
76796      */
76797     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76798         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76799         var pendingExpressions;
76800         var pendingDeclarations = [];
76801         var declarations = [];
76802         var flattenContext = {
76803             context: context,
76804             level: level,
76805             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76806             hoistTempVariables: hoistTempVariables,
76807             emitExpression: emitExpression,
76808             emitBindingOrAssignment: emitBindingOrAssignment,
76809             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76810             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76811             createArrayBindingOrAssignmentElement: makeBindingElement,
76812             visitor: visitor
76813         };
76814         if (ts.isVariableDeclaration(node)) {
76815             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76816             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76817                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
76818                 // If the right-hand value of the assignment is also an assignment target then
76819                 // we need to cache the right-hand value.
76820                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
76821                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
76822             }
76823         }
76824         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
76825         if (pendingExpressions) {
76826             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76827             if (hoistTempVariables) {
76828                 var value = ts.inlineExpressions(pendingExpressions);
76829                 pendingExpressions = undefined;
76830                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
76831             }
76832             else {
76833                 context.hoistVariableDeclaration(temp);
76834                 var pendingDeclaration = ts.last(pendingDeclarations);
76835                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
76836                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
76837                 pendingDeclaration.value = temp;
76838             }
76839         }
76840         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
76841             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
76842             var variable = ts.createVariableDeclaration(name, 
76843             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
76844             variable.original = original;
76845             ts.setTextRange(variable, location);
76846             ts.aggregateTransformFlags(variable);
76847             declarations.push(variable);
76848         }
76849         return declarations;
76850         function emitExpression(value) {
76851             pendingExpressions = ts.append(pendingExpressions, value);
76852         }
76853         function emitBindingOrAssignment(target, value, location, original) {
76854             ts.Debug.assertNode(target, ts.isBindingName);
76855             if (pendingExpressions) {
76856                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
76857                 pendingExpressions = undefined;
76858             }
76859             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
76860         }
76861     }
76862     ts.flattenDestructuringBinding = flattenDestructuringBinding;
76863     /**
76864      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
76865      *
76866      * @param flattenContext Options used to control flattening.
76867      * @param element The element to flatten.
76868      * @param value The current RHS value to assign to the element.
76869      * @param location The location to use for source maps and comments.
76870      * @param skipInitializer An optional value indicating whether to include the initializer
76871      * for the element.
76872      */
76873     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
76874         if (!skipInitializer) {
76875             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
76876             if (initializer) {
76877                 // Combine value and initializer
76878                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
76879             }
76880             else if (!value) {
76881                 // Use 'void 0' in absence of value and initializer
76882                 value = ts.createVoidZero();
76883             }
76884         }
76885         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76886         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
76887             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76888         }
76889         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
76890             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76891         }
76892         else {
76893             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
76894         }
76895     }
76896     /**
76897      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
76898      *
76899      * @param flattenContext Options used to control flattening.
76900      * @param parent The parent element of the pattern.
76901      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
76902      * @param value The current RHS value to assign to the element.
76903      * @param location The location to use for source maps and comments.
76904      */
76905     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76906         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76907         var numElements = elements.length;
76908         if (numElements !== 1) {
76909             // For anything other than a single-element destructuring we need to generate a temporary
76910             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76911             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76912             // so in that case, we'll intentionally create that temporary.
76913             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76914             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76915         }
76916         var bindingElements;
76917         var computedTempVariables;
76918         for (var i = 0; i < numElements; i++) {
76919             var element = elements[i];
76920             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
76921                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
76922                 if (flattenContext.level >= 1 /* ObjectRest */
76923                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76924                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76925                     && !ts.isComputedPropertyName(propertyName)) {
76926                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
76927                 }
76928                 else {
76929                     if (bindingElements) {
76930                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76931                         bindingElements = undefined;
76932                     }
76933                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
76934                     if (ts.isComputedPropertyName(propertyName)) {
76935                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
76936                     }
76937                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
76938                 }
76939             }
76940             else if (i === numElements - 1) {
76941                 if (bindingElements) {
76942                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76943                     bindingElements = undefined;
76944                 }
76945                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
76946                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
76947             }
76948         }
76949         if (bindingElements) {
76950             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76951         }
76952     }
76953     /**
76954      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
76955      *
76956      * @param flattenContext Options used to control flattening.
76957      * @param parent The parent element of the pattern.
76958      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
76959      * @param value The current RHS value to assign to the element.
76960      * @param location The location to use for source maps and comments.
76961      */
76962     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76963         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76964         var numElements = elements.length;
76965         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
76966             // Read the elements of the iterable into an array
76967             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
76968                 ? undefined
76969                 : numElements, location), 
76970             /*reuseIdentifierExpressions*/ false, location);
76971         }
76972         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
76973             || ts.every(elements, ts.isOmittedExpression)) {
76974             // For anything other than a single-element destructuring we need to generate a temporary
76975             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76976             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76977             // so in that case, we'll intentionally create that temporary.
76978             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
76979             // then we will create temporary variable.
76980             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76981             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76982         }
76983         var bindingElements;
76984         var restContainingElements;
76985         for (var i = 0; i < numElements; i++) {
76986             var element = elements[i];
76987             if (flattenContext.level >= 1 /* ObjectRest */) {
76988                 // If an array pattern contains an ObjectRest, we must cache the result so that we
76989                 // can perform the ObjectRest destructuring in a different declaration
76990                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
76991                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76992                     if (flattenContext.hoistTempVariables) {
76993                         flattenContext.context.hoistVariableDeclaration(temp);
76994                     }
76995                     restContainingElements = ts.append(restContainingElements, [temp, element]);
76996                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
76997                 }
76998                 else {
76999                     bindingElements = ts.append(bindingElements, element);
77000                 }
77001             }
77002             else if (ts.isOmittedExpression(element)) {
77003                 continue;
77004             }
77005             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77006                 var rhsValue = ts.createElementAccess(value, i);
77007                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77008             }
77009             else if (i === numElements - 1) {
77010                 var rhsValue = ts.createArraySlice(value, i);
77011                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77012             }
77013         }
77014         if (bindingElements) {
77015             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77016         }
77017         if (restContainingElements) {
77018             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77019                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77020                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77021             }
77022         }
77023     }
77024     /**
77025      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77026      *
77027      * @param flattenContext Options used to control flattening.
77028      * @param value The RHS value to test.
77029      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77030      * @param location The location to use for source maps and comments.
77031      */
77032     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77033         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77034         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77035     }
77036     /**
77037      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77038      * right-hand side of a transformed destructuring assignment.
77039      *
77040      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77041      *
77042      * @param flattenContext Options used to control flattening.
77043      * @param value The RHS value that is the source of the property.
77044      * @param propertyName The destructuring property name.
77045      */
77046     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77047         if (ts.isComputedPropertyName(propertyName)) {
77048             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77049             return ts.createElementAccess(value, argumentExpression);
77050         }
77051         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77052             var argumentExpression = ts.getSynthesizedClone(propertyName);
77053             argumentExpression.text = argumentExpression.text;
77054             return ts.createElementAccess(value, argumentExpression);
77055         }
77056         else {
77057             var name = ts.createIdentifier(ts.idText(propertyName));
77058             return ts.createPropertyAccess(value, name);
77059         }
77060     }
77061     /**
77062      * Ensures that there exists a declared identifier whose value holds the given expression.
77063      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77064      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77065      *
77066      * @param flattenContext Options used to control flattening.
77067      * @param value the expression whose value needs to be bound.
77068      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77069      * false if it is necessary to always emit an identifier.
77070      * @param location The location to use for source maps and comments.
77071      */
77072     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77073         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77074             return value;
77075         }
77076         else {
77077             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77078             if (flattenContext.hoistTempVariables) {
77079                 flattenContext.context.hoistVariableDeclaration(temp);
77080                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77081             }
77082             else {
77083                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77084             }
77085             return temp;
77086         }
77087     }
77088     function makeArrayBindingPattern(elements) {
77089         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77090         return ts.createArrayBindingPattern(elements);
77091     }
77092     function makeArrayAssignmentPattern(elements) {
77093         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77094     }
77095     function makeObjectBindingPattern(elements) {
77096         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77097         return ts.createObjectBindingPattern(elements);
77098     }
77099     function makeObjectAssignmentPattern(elements) {
77100         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77101     }
77102     function makeBindingElement(name) {
77103         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77104     }
77105     function makeAssignmentElement(name) {
77106         return name;
77107     }
77108     ts.restHelper = {
77109         name: "typescript:rest",
77110         importName: "__rest",
77111         scoped: false,
77112         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            };"
77113     };
77114     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77115      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77116      */
77117     function createRestCall(context, value, elements, computedTempVariables, location) {
77118         context.requestEmitHelper(ts.restHelper);
77119         var propertyNames = [];
77120         var computedTempVariableOffset = 0;
77121         for (var i = 0; i < elements.length - 1; i++) {
77122             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77123             if (propertyName) {
77124                 if (ts.isComputedPropertyName(propertyName)) {
77125                     var temp = computedTempVariables[computedTempVariableOffset];
77126                     computedTempVariableOffset++;
77127                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77128                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77129                 }
77130                 else {
77131                     propertyNames.push(ts.createLiteral(propertyName));
77132                 }
77133             }
77134         }
77135         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77136         /*typeArguments*/ undefined, [
77137             value,
77138             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77139         ]);
77140     }
77141 })(ts || (ts = {}));
77142 /*@internal*/
77143 var ts;
77144 (function (ts) {
77145     var ProcessLevel;
77146     (function (ProcessLevel) {
77147         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77148         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77149     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77150     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77151         // Visit the tag expression
77152         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77153         // Build up the template arguments and the raw and cooked strings for the template.
77154         // We start out with 'undefined' for the first argument and revisit later
77155         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77156         var templateArguments = [undefined];
77157         var cookedStrings = [];
77158         var rawStrings = [];
77159         var template = node.template;
77160         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77161             return node;
77162         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77163             cookedStrings.push(createTemplateCooked(template));
77164             rawStrings.push(getRawLiteral(template, currentSourceFile));
77165         }
77166         else {
77167             cookedStrings.push(createTemplateCooked(template.head));
77168             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77169             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77170                 var templateSpan = _a[_i];
77171                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77172                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77173                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77174             }
77175         }
77176         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77177         // Create a variable to cache the template object if we're in a module.
77178         // Do not do this in the global scope, as any variable we currently generate could conflict with
77179         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77180         if (ts.isExternalModule(currentSourceFile)) {
77181             var tempVar = ts.createUniqueName("templateObject");
77182             recordTaggedTemplateString(tempVar);
77183             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77184         }
77185         else {
77186             templateArguments[0] = helperCall;
77187         }
77188         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77189     }
77190     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77191     function createTemplateCooked(template) {
77192         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77193     }
77194     /**
77195      * Creates an ES5 compatible literal from an ES6 template literal.
77196      *
77197      * @param node The ES6 template literal.
77198      */
77199     function getRawLiteral(node, currentSourceFile) {
77200         // Find original source text, since we need to emit the raw strings of the tagged template.
77201         // The raw strings contain the (escaped) strings of what the user wrote.
77202         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77203         var text = node.rawText;
77204         if (text === undefined) {
77205             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77206             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77207             // thus we need to remove those characters.
77208             // First template piece starts with "`", others with "}"
77209             // Last template piece ends with "`", others with "${"
77210             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77211             text = text.substring(1, text.length - (isLast ? 1 : 2));
77212         }
77213         // Newline normalization:
77214         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77215         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77216         text = text.replace(/\r\n?/g, "\n");
77217         return ts.setTextRange(ts.createLiteral(text), node);
77218     }
77219     function createTemplateObjectHelper(context, cooked, raw) {
77220         context.requestEmitHelper(ts.templateObjectHelper);
77221         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77222         /*typeArguments*/ undefined, [
77223             cooked,
77224             raw
77225         ]);
77226     }
77227     ts.templateObjectHelper = {
77228         name: "typescript:makeTemplateObject",
77229         importName: "__makeTemplateObject",
77230         scoped: false,
77231         priority: 0,
77232         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            };"
77233     };
77234 })(ts || (ts = {}));
77235 /*@internal*/
77236 var ts;
77237 (function (ts) {
77238     /**
77239      * Indicates whether to emit type metadata in the new format.
77240      */
77241     var USE_NEW_TYPE_METADATA_FORMAT = false;
77242     var TypeScriptSubstitutionFlags;
77243     (function (TypeScriptSubstitutionFlags) {
77244         /** Enables substitutions for decorated classes. */
77245         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77246         /** Enables substitutions for namespace exports. */
77247         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77248         /* Enables substitutions for unqualified enum members */
77249         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77250     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77251     var ClassFacts;
77252     (function (ClassFacts) {
77253         ClassFacts[ClassFacts["None"] = 0] = "None";
77254         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77255         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77256         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77257         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77258         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77259         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77260         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77261         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77262         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77263         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77264         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77265         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77266     })(ClassFacts || (ClassFacts = {}));
77267     function transformTypeScript(context) {
77268         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77269         var resolver = context.getEmitResolver();
77270         var compilerOptions = context.getCompilerOptions();
77271         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77272         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77273         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77274         // Save the previous transformation hooks.
77275         var previousOnEmitNode = context.onEmitNode;
77276         var previousOnSubstituteNode = context.onSubstituteNode;
77277         // Set new transformation hooks.
77278         context.onEmitNode = onEmitNode;
77279         context.onSubstituteNode = onSubstituteNode;
77280         // Enable substitution for property/element access to emit const enum values.
77281         context.enableSubstitution(194 /* PropertyAccessExpression */);
77282         context.enableSubstitution(195 /* ElementAccessExpression */);
77283         // These variables contain state that changes as we descend into the tree.
77284         var currentSourceFile;
77285         var currentNamespace;
77286         var currentNamespaceContainerName;
77287         var currentLexicalScope;
77288         var currentNameScope;
77289         var currentScopeFirstDeclarationsOfName;
77290         var currentClassHasParameterProperties;
77291         /**
77292          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77293          * They are persisted between each SourceFile transformation and should not be reset.
77294          */
77295         var enabledSubstitutions;
77296         /**
77297          * A map that keeps track of aliases created for classes with decorators to avoid issues
77298          * with the double-binding behavior of classes.
77299          */
77300         var classAliases;
77301         /**
77302          * Keeps track of whether we are within any containing namespaces when performing
77303          * just-in-time substitution while printing an expression identifier.
77304          */
77305         var applicableSubstitutions;
77306         return transformSourceFileOrBundle;
77307         function transformSourceFileOrBundle(node) {
77308             if (node.kind === 291 /* Bundle */) {
77309                 return transformBundle(node);
77310             }
77311             return transformSourceFile(node);
77312         }
77313         function transformBundle(node) {
77314             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77315                 if (prepend.kind === 293 /* InputFiles */) {
77316                     return ts.createUnparsedSourceFile(prepend, "js");
77317                 }
77318                 return prepend;
77319             }));
77320         }
77321         /**
77322          * Transform TypeScript-specific syntax in a SourceFile.
77323          *
77324          * @param node A SourceFile node.
77325          */
77326         function transformSourceFile(node) {
77327             if (node.isDeclarationFile) {
77328                 return node;
77329             }
77330             currentSourceFile = node;
77331             var visited = saveStateAndInvoke(node, visitSourceFile);
77332             ts.addEmitHelpers(visited, context.readEmitHelpers());
77333             currentSourceFile = undefined;
77334             return visited;
77335         }
77336         /**
77337          * Visits a node, saving and restoring state variables on the stack.
77338          *
77339          * @param node The node to visit.
77340          */
77341         function saveStateAndInvoke(node, f) {
77342             // Save state
77343             var savedCurrentScope = currentLexicalScope;
77344             var savedCurrentNameScope = currentNameScope;
77345             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77346             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77347             // Handle state changes before visiting a node.
77348             onBeforeVisitNode(node);
77349             var visited = f(node);
77350             // Restore state
77351             if (currentLexicalScope !== savedCurrentScope) {
77352                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77353             }
77354             currentLexicalScope = savedCurrentScope;
77355             currentNameScope = savedCurrentNameScope;
77356             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77357             return visited;
77358         }
77359         /**
77360          * Performs actions that should always occur immediately before visiting a node.
77361          *
77362          * @param node The node to visit.
77363          */
77364         function onBeforeVisitNode(node) {
77365             switch (node.kind) {
77366                 case 290 /* SourceFile */:
77367                 case 251 /* CaseBlock */:
77368                 case 250 /* ModuleBlock */:
77369                 case 223 /* Block */:
77370                     currentLexicalScope = node;
77371                     currentNameScope = undefined;
77372                     currentScopeFirstDeclarationsOfName = undefined;
77373                     break;
77374                 case 245 /* ClassDeclaration */:
77375                 case 244 /* FunctionDeclaration */:
77376                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77377                         break;
77378                     }
77379                     // Record these declarations provided that they have a name.
77380                     if (node.name) {
77381                         recordEmittedDeclarationInScope(node);
77382                     }
77383                     else {
77384                         // These nodes should always have names unless they are default-exports;
77385                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77386                         // programs may also have an undefined name.
77387                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77388                     }
77389                     if (ts.isClassDeclaration(node)) {
77390                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77391                         currentNameScope = node;
77392                     }
77393                     break;
77394             }
77395         }
77396         /**
77397          * General-purpose node visitor.
77398          *
77399          * @param node The node to visit.
77400          */
77401         function visitor(node) {
77402             return saveStateAndInvoke(node, visitorWorker);
77403         }
77404         /**
77405          * Visits and possibly transforms any node.
77406          *
77407          * @param node The node to visit.
77408          */
77409         function visitorWorker(node) {
77410             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77411                 return visitTypeScript(node);
77412             }
77413             return node;
77414         }
77415         /**
77416          * Specialized visitor that visits the immediate children of a SourceFile.
77417          *
77418          * @param node The node to visit.
77419          */
77420         function sourceElementVisitor(node) {
77421             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77422         }
77423         /**
77424          * Specialized visitor that visits the immediate children of a SourceFile.
77425          *
77426          * @param node The node to visit.
77427          */
77428         function sourceElementVisitorWorker(node) {
77429             switch (node.kind) {
77430                 case 254 /* ImportDeclaration */:
77431                 case 253 /* ImportEqualsDeclaration */:
77432                 case 259 /* ExportAssignment */:
77433                 case 260 /* ExportDeclaration */:
77434                     return visitEllidableStatement(node);
77435                 default:
77436                     return visitorWorker(node);
77437             }
77438         }
77439         function visitEllidableStatement(node) {
77440             var parsed = ts.getParseTreeNode(node);
77441             if (parsed !== node) {
77442                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77443                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77444                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77445                 // and will trigger debug failures when debug verbosity is turned up
77446                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77447                     // This node contains TypeScript, so we should visit its children.
77448                     return ts.visitEachChild(node, visitor, context);
77449                 }
77450                 // Otherwise, we can just return the node
77451                 return node;
77452             }
77453             switch (node.kind) {
77454                 case 254 /* ImportDeclaration */:
77455                     return visitImportDeclaration(node);
77456                 case 253 /* ImportEqualsDeclaration */:
77457                     return visitImportEqualsDeclaration(node);
77458                 case 259 /* ExportAssignment */:
77459                     return visitExportAssignment(node);
77460                 case 260 /* ExportDeclaration */:
77461                     return visitExportDeclaration(node);
77462                 default:
77463                     ts.Debug.fail("Unhandled ellided statement");
77464             }
77465         }
77466         /**
77467          * Specialized visitor that visits the immediate children of a namespace.
77468          *
77469          * @param node The node to visit.
77470          */
77471         function namespaceElementVisitor(node) {
77472             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77473         }
77474         /**
77475          * Specialized visitor that visits the immediate children of a namespace.
77476          *
77477          * @param node The node to visit.
77478          */
77479         function namespaceElementVisitorWorker(node) {
77480             if (node.kind === 260 /* ExportDeclaration */ ||
77481                 node.kind === 254 /* ImportDeclaration */ ||
77482                 node.kind === 255 /* ImportClause */ ||
77483                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77484                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77485                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77486                 return undefined;
77487             }
77488             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77489                 return visitTypeScript(node);
77490             }
77491             return node;
77492         }
77493         /**
77494          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77495          *
77496          * @param node The node to visit.
77497          */
77498         function classElementVisitor(node) {
77499             return saveStateAndInvoke(node, classElementVisitorWorker);
77500         }
77501         /**
77502          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77503          *
77504          * @param node The node to visit.
77505          */
77506         function classElementVisitorWorker(node) {
77507             switch (node.kind) {
77508                 case 162 /* Constructor */:
77509                     return visitConstructor(node);
77510                 case 159 /* PropertyDeclaration */:
77511                     // Property declarations are not TypeScript syntax, but they must be visited
77512                     // for the decorator transformation.
77513                     return visitPropertyDeclaration(node);
77514                 case 167 /* IndexSignature */:
77515                 case 163 /* GetAccessor */:
77516                 case 164 /* SetAccessor */:
77517                 case 161 /* MethodDeclaration */:
77518                     // Fallback to the default visit behavior.
77519                     return visitorWorker(node);
77520                 case 222 /* SemicolonClassElement */:
77521                     return node;
77522                 default:
77523                     return ts.Debug.failBadSyntaxKind(node);
77524             }
77525         }
77526         function modifierVisitor(node) {
77527             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77528                 return undefined;
77529             }
77530             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77531                 return undefined;
77532             }
77533             return node;
77534         }
77535         /**
77536          * Branching visitor, visits a TypeScript syntax node.
77537          *
77538          * @param node The node to visit.
77539          */
77540         function visitTypeScript(node) {
77541             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77542                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77543                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77544                 return ts.createNotEmittedStatement(node);
77545             }
77546             switch (node.kind) {
77547                 case 89 /* ExportKeyword */:
77548                 case 84 /* DefaultKeyword */:
77549                     // ES6 export and default modifiers are elided when inside a namespace.
77550                     return currentNamespace ? undefined : node;
77551                 case 119 /* PublicKeyword */:
77552                 case 117 /* PrivateKeyword */:
77553                 case 118 /* ProtectedKeyword */:
77554                 case 122 /* AbstractKeyword */:
77555                 case 81 /* ConstKeyword */:
77556                 case 130 /* DeclareKeyword */:
77557                 case 138 /* ReadonlyKeyword */:
77558                 // TypeScript accessibility and readonly modifiers are elided
77559                 // falls through
77560                 case 174 /* ArrayType */:
77561                 case 175 /* TupleType */:
77562                 case 176 /* OptionalType */:
77563                 case 177 /* RestType */:
77564                 case 173 /* TypeLiteral */:
77565                 case 168 /* TypePredicate */:
77566                 case 155 /* TypeParameter */:
77567                 case 125 /* AnyKeyword */:
77568                 case 148 /* UnknownKeyword */:
77569                 case 128 /* BooleanKeyword */:
77570                 case 143 /* StringKeyword */:
77571                 case 140 /* NumberKeyword */:
77572                 case 137 /* NeverKeyword */:
77573                 case 110 /* VoidKeyword */:
77574                 case 144 /* SymbolKeyword */:
77575                 case 171 /* ConstructorType */:
77576                 case 170 /* FunctionType */:
77577                 case 172 /* TypeQuery */:
77578                 case 169 /* TypeReference */:
77579                 case 178 /* UnionType */:
77580                 case 179 /* IntersectionType */:
77581                 case 180 /* ConditionalType */:
77582                 case 182 /* ParenthesizedType */:
77583                 case 183 /* ThisType */:
77584                 case 184 /* TypeOperator */:
77585                 case 185 /* IndexedAccessType */:
77586                 case 186 /* MappedType */:
77587                 case 187 /* LiteralType */:
77588                 // TypeScript type nodes are elided.
77589                 // falls through
77590                 case 167 /* IndexSignature */:
77591                 // TypeScript index signatures are elided.
77592                 // falls through
77593                 case 157 /* Decorator */:
77594                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77595                 // falls through
77596                 case 247 /* TypeAliasDeclaration */:
77597                     // TypeScript type-only declarations are elided.
77598                     return undefined;
77599                 case 159 /* PropertyDeclaration */:
77600                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77601                     return visitPropertyDeclaration(node);
77602                 case 252 /* NamespaceExportDeclaration */:
77603                     // TypeScript namespace export declarations are elided.
77604                     return undefined;
77605                 case 162 /* Constructor */:
77606                     return visitConstructor(node);
77607                 case 246 /* InterfaceDeclaration */:
77608                     // TypeScript interfaces are elided, but some comments may be preserved.
77609                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77610                     return ts.createNotEmittedStatement(node);
77611                 case 245 /* ClassDeclaration */:
77612                     // This may be a class declaration with TypeScript syntax extensions.
77613                     //
77614                     // TypeScript class syntax extensions include:
77615                     // - decorators
77616                     // - optional `implements` heritage clause
77617                     // - parameter property assignments in the constructor
77618                     // - index signatures
77619                     // - method overload signatures
77620                     return visitClassDeclaration(node);
77621                 case 214 /* ClassExpression */:
77622                     // This may be a class expression with TypeScript syntax extensions.
77623                     //
77624                     // TypeScript class syntax extensions include:
77625                     // - decorators
77626                     // - optional `implements` heritage clause
77627                     // - parameter property assignments in the constructor
77628                     // - index signatures
77629                     // - method overload signatures
77630                     return visitClassExpression(node);
77631                 case 279 /* HeritageClause */:
77632                     // This may be a heritage clause with TypeScript syntax extensions.
77633                     //
77634                     // TypeScript heritage clause extensions include:
77635                     // - `implements` clause
77636                     return visitHeritageClause(node);
77637                 case 216 /* ExpressionWithTypeArguments */:
77638                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77639                     return visitExpressionWithTypeArguments(node);
77640                 case 161 /* MethodDeclaration */:
77641                     // TypeScript method declarations may have decorators, modifiers
77642                     // or type annotations.
77643                     return visitMethodDeclaration(node);
77644                 case 163 /* GetAccessor */:
77645                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77646                     return visitGetAccessor(node);
77647                 case 164 /* SetAccessor */:
77648                     // Set Accessors can have TypeScript modifiers and type annotations.
77649                     return visitSetAccessor(node);
77650                 case 244 /* FunctionDeclaration */:
77651                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77652                     return visitFunctionDeclaration(node);
77653                 case 201 /* FunctionExpression */:
77654                     // TypeScript function expressions can have modifiers and type annotations.
77655                     return visitFunctionExpression(node);
77656                 case 202 /* ArrowFunction */:
77657                     // TypeScript arrow functions can have modifiers and type annotations.
77658                     return visitArrowFunction(node);
77659                 case 156 /* Parameter */:
77660                     // This may be a parameter declaration with TypeScript syntax extensions.
77661                     //
77662                     // TypeScript parameter declaration syntax extensions include:
77663                     // - decorators
77664                     // - accessibility modifiers
77665                     // - the question mark (?) token for optional parameters
77666                     // - type annotations
77667                     // - this parameters
77668                     return visitParameter(node);
77669                 case 200 /* ParenthesizedExpression */:
77670                     // ParenthesizedExpressions are TypeScript if their expression is a
77671                     // TypeAssertion or AsExpression
77672                     return visitParenthesizedExpression(node);
77673                 case 199 /* TypeAssertionExpression */:
77674                 case 217 /* AsExpression */:
77675                     // TypeScript type assertions are removed, but their subtrees are preserved.
77676                     return visitAssertionExpression(node);
77677                 case 196 /* CallExpression */:
77678                     return visitCallExpression(node);
77679                 case 197 /* NewExpression */:
77680                     return visitNewExpression(node);
77681                 case 198 /* TaggedTemplateExpression */:
77682                     return visitTaggedTemplateExpression(node);
77683                 case 218 /* NonNullExpression */:
77684                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77685                     return visitNonNullExpression(node);
77686                 case 248 /* EnumDeclaration */:
77687                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77688                     return visitEnumDeclaration(node);
77689                 case 225 /* VariableStatement */:
77690                     // TypeScript namespace exports for variable statements must be transformed.
77691                     return visitVariableStatement(node);
77692                 case 242 /* VariableDeclaration */:
77693                     return visitVariableDeclaration(node);
77694                 case 249 /* ModuleDeclaration */:
77695                     // TypeScript namespace declarations must be transformed.
77696                     return visitModuleDeclaration(node);
77697                 case 253 /* ImportEqualsDeclaration */:
77698                     // TypeScript namespace or external module import.
77699                     return visitImportEqualsDeclaration(node);
77700                 case 267 /* JsxSelfClosingElement */:
77701                     return visitJsxSelfClosingElement(node);
77702                 case 268 /* JsxOpeningElement */:
77703                     return visitJsxJsxOpeningElement(node);
77704                 default:
77705                     // node contains some other TypeScript syntax
77706                     return ts.visitEachChild(node, visitor, context);
77707             }
77708         }
77709         function visitSourceFile(node) {
77710             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77711                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77712                 !ts.isJsonSourceFile(node);
77713             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77714         }
77715         /**
77716          * Tests whether we should emit a __decorate call for a class declaration.
77717          */
77718         function shouldEmitDecorateCallForClass(node) {
77719             if (node.decorators && node.decorators.length > 0) {
77720                 return true;
77721             }
77722             var constructor = ts.getFirstConstructorWithBody(node);
77723             if (constructor) {
77724                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77725             }
77726             return false;
77727         }
77728         /**
77729          * Tests whether we should emit a __decorate call for a parameter declaration.
77730          */
77731         function shouldEmitDecorateCallForParameter(parameter) {
77732             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77733         }
77734         function getClassFacts(node, staticProperties) {
77735             var facts = 0 /* None */;
77736             if (ts.some(staticProperties))
77737                 facts |= 1 /* HasStaticInitializedProperties */;
77738             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77739             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77740                 facts |= 64 /* IsDerivedClass */;
77741             if (shouldEmitDecorateCallForClass(node))
77742                 facts |= 2 /* HasConstructorDecorators */;
77743             if (ts.childIsDecorated(node))
77744                 facts |= 4 /* HasMemberDecorators */;
77745             if (isExportOfNamespace(node))
77746                 facts |= 8 /* IsExportOfNamespace */;
77747             else if (isDefaultExternalModuleExport(node))
77748                 facts |= 32 /* IsDefaultExternalExport */;
77749             else if (isNamedExternalModuleExport(node))
77750                 facts |= 16 /* IsNamedExternalExport */;
77751             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77752                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77753             return facts;
77754         }
77755         function hasTypeScriptClassSyntax(node) {
77756             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77757         }
77758         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77759             return ts.some(node.decorators)
77760                 || ts.some(node.typeParameters)
77761                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77762                 || ts.some(node.members, hasTypeScriptClassSyntax);
77763         }
77764         function visitClassDeclaration(node) {
77765             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77766                 return ts.visitEachChild(node, visitor, context);
77767             }
77768             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77769             var facts = getClassFacts(node, staticProperties);
77770             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77771                 context.startLexicalEnvironment();
77772             }
77773             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77774             var classStatement = facts & 2 /* HasConstructorDecorators */
77775                 ? createClassDeclarationHeadWithDecorators(node, name)
77776                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77777             var statements = [classStatement];
77778             // Write any decorators of the node.
77779             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77780             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77781             addConstructorDecorationStatement(statements, node);
77782             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77783                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77784                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77785                 // looks something like:
77786                 //
77787                 //  var C = function () {
77788                 //      class C {
77789                 //      }
77790                 //      C.static_prop = 1;
77791                 //      return C;
77792                 //  }();
77793                 //
77794                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77795                 var localName = ts.getInternalName(node);
77796                 // The following partially-emitted expression exists purely to align our sourcemap
77797                 // emit with the original emitter.
77798                 var outer = ts.createPartiallyEmittedExpression(localName);
77799                 outer.end = closingBraceLocation.end;
77800                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77801                 var statement = ts.createReturn(outer);
77802                 statement.pos = closingBraceLocation.pos;
77803                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77804                 statements.push(statement);
77805                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77806                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77807                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77808                 var varStatement = ts.createVariableStatement(
77809                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77810                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77811                     /*type*/ undefined, iife)
77812                 ]));
77813                 ts.setOriginalNode(varStatement, node);
77814                 ts.setCommentRange(varStatement, node);
77815                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77816                 ts.startOnNewLine(varStatement);
77817                 statements = [varStatement];
77818             }
77819             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
77820             // Otherwise, if the class was exported at the top level and was decorated, emit an export
77821             // declaration or export default for the class.
77822             if (facts & 8 /* IsExportOfNamespace */) {
77823                 addExportMemberAssignment(statements, node);
77824             }
77825             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
77826                 if (facts & 32 /* IsDefaultExternalExport */) {
77827                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77828                 }
77829                 else if (facts & 16 /* IsNamedExternalExport */) {
77830                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77831                 }
77832             }
77833             if (statements.length > 1) {
77834                 // Add a DeclarationMarker as a marker for the end of the declaration
77835                 statements.push(ts.createEndOfDeclarationMarker(node));
77836                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
77837             }
77838             return ts.singleOrMany(statements);
77839         }
77840         /**
77841          * Transforms a non-decorated class declaration and appends the resulting statements.
77842          *
77843          * @param node A ClassDeclaration node.
77844          * @param name The name of the class.
77845          * @param facts Precomputed facts about the class.
77846          */
77847         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
77848             //  ${modifiers} class ${name} ${heritageClauses} {
77849             //      ${members}
77850             //  }
77851             // we do not emit modifiers on the declaration if we are emitting an IIFE
77852             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
77853                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
77854                 : undefined;
77855             var classDeclaration = ts.createClassDeclaration(
77856             /*decorators*/ undefined, modifiers, name, 
77857             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77858             // To better align with the old emitter, we should not emit a trailing source map
77859             // entry if the class has static properties.
77860             var emitFlags = ts.getEmitFlags(node);
77861             if (facts & 1 /* HasStaticInitializedProperties */) {
77862                 emitFlags |= 32 /* NoTrailingSourceMap */;
77863             }
77864             ts.aggregateTransformFlags(classDeclaration);
77865             ts.setTextRange(classDeclaration, node);
77866             ts.setOriginalNode(classDeclaration, node);
77867             ts.setEmitFlags(classDeclaration, emitFlags);
77868             return classDeclaration;
77869         }
77870         /**
77871          * Transforms a decorated class declaration and appends the resulting statements. If
77872          * the class requires an alias to avoid issues with double-binding, the alias is returned.
77873          */
77874         function createClassDeclarationHeadWithDecorators(node, name) {
77875             // When we emit an ES6 class that has a class decorator, we must tailor the
77876             // emit to certain specific cases.
77877             //
77878             // In the simplest case, we emit the class declaration as a let declaration, and
77879             // evaluate decorators after the close of the class body:
77880             //
77881             //  [Example 1]
77882             //  ---------------------------------------------------------------------
77883             //  TypeScript                      | Javascript
77884             //  ---------------------------------------------------------------------
77885             //  @dec                            | let C = class C {
77886             //  class C {                       | }
77887             //  }                               | C = __decorate([dec], C);
77888             //  ---------------------------------------------------------------------
77889             //  @dec                            | let C = class C {
77890             //  export class C {                | }
77891             //  }                               | C = __decorate([dec], C);
77892             //                                  | export { C };
77893             //  ---------------------------------------------------------------------
77894             //
77895             // If a class declaration contains a reference to itself *inside* of the class body,
77896             // this introduces two bindings to the class: One outside of the class body, and one
77897             // inside of the class body. If we apply decorators as in [Example 1] above, there
77898             // is the possibility that the decorator `dec` will return a new value for the
77899             // constructor, which would result in the binding inside of the class no longer
77900             // pointing to the same reference as the binding outside of the class.
77901             //
77902             // As a result, we must instead rewrite all references to the class *inside* of the
77903             // class body to instead point to a local temporary alias for the class:
77904             //
77905             //  [Example 2]
77906             //  ---------------------------------------------------------------------
77907             //  TypeScript                      | Javascript
77908             //  ---------------------------------------------------------------------
77909             //  @dec                            | let C = C_1 = class C {
77910             //  class C {                       |   static x() { return C_1.y; }
77911             //    static x() { return C.y; }    | }
77912             //    static y = 1;                 | C.y = 1;
77913             //  }                               | C = C_1 = __decorate([dec], C);
77914             //                                  | var C_1;
77915             //  ---------------------------------------------------------------------
77916             //  @dec                            | let C = class C {
77917             //  export class C {                |   static x() { return C_1.y; }
77918             //    static x() { return C.y; }    | }
77919             //    static y = 1;                 | C.y = 1;
77920             //  }                               | C = C_1 = __decorate([dec], C);
77921             //                                  | export { C };
77922             //                                  | var C_1;
77923             //  ---------------------------------------------------------------------
77924             //
77925             // If a class declaration is the default export of a module, we instead emit
77926             // the export after the decorated declaration:
77927             //
77928             //  [Example 3]
77929             //  ---------------------------------------------------------------------
77930             //  TypeScript                      | Javascript
77931             //  ---------------------------------------------------------------------
77932             //  @dec                            | let default_1 = class {
77933             //  export default class {          | }
77934             //  }                               | default_1 = __decorate([dec], default_1);
77935             //                                  | export default default_1;
77936             //  ---------------------------------------------------------------------
77937             //  @dec                            | let C = class C {
77938             //  export default class C {        | }
77939             //  }                               | C = __decorate([dec], C);
77940             //                                  | export default C;
77941             //  ---------------------------------------------------------------------
77942             //
77943             // If the class declaration is the default export and a reference to itself
77944             // inside of the class body, we must emit both an alias for the class *and*
77945             // move the export after the declaration:
77946             //
77947             //  [Example 4]
77948             //  ---------------------------------------------------------------------
77949             //  TypeScript                      | Javascript
77950             //  ---------------------------------------------------------------------
77951             //  @dec                            | let C = class C {
77952             //  export default class C {        |   static x() { return C_1.y; }
77953             //    static x() { return C.y; }    | }
77954             //    static y = 1;                 | C.y = 1;
77955             //  }                               | C = C_1 = __decorate([dec], C);
77956             //                                  | export default C;
77957             //                                  | var C_1;
77958             //  ---------------------------------------------------------------------
77959             //
77960             var location = ts.moveRangePastDecorators(node);
77961             var classAlias = getClassAliasIfNeeded(node);
77962             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
77963             //  ... = class ${name} ${heritageClauses} {
77964             //      ${members}
77965             //  }
77966             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
77967             var members = transformClassMembers(node);
77968             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
77969             ts.aggregateTransformFlags(classExpression);
77970             ts.setOriginalNode(classExpression, node);
77971             ts.setTextRange(classExpression, location);
77972             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
77973             //                                         or decoratedClassAlias if the class contain self-reference.
77974             var statement = ts.createVariableStatement(
77975             /*modifiers*/ undefined, ts.createVariableDeclarationList([
77976                 ts.createVariableDeclaration(declName, 
77977                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
77978             ], 1 /* Let */));
77979             ts.setOriginalNode(statement, node);
77980             ts.setTextRange(statement, location);
77981             ts.setCommentRange(statement, node);
77982             return statement;
77983         }
77984         function visitClassExpression(node) {
77985             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
77986                 return ts.visitEachChild(node, visitor, context);
77987             }
77988             var classExpression = ts.createClassExpression(
77989             /*modifiers*/ undefined, node.name, 
77990             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77991             ts.aggregateTransformFlags(classExpression);
77992             ts.setOriginalNode(classExpression, node);
77993             ts.setTextRange(classExpression, node);
77994             return classExpression;
77995         }
77996         /**
77997          * Transforms the members of a class.
77998          *
77999          * @param node The current class.
78000          */
78001         function transformClassMembers(node) {
78002             var members = [];
78003             var constructor = ts.getFirstConstructorWithBody(node);
78004             var parametersWithPropertyAssignments = constructor &&
78005                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78006             if (parametersWithPropertyAssignments) {
78007                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78008                     var parameter = parametersWithPropertyAssignments_1[_i];
78009                     if (ts.isIdentifier(parameter.name)) {
78010                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78011                         /*decorators*/ undefined, 
78012                         /*modifiers*/ undefined, parameter.name, 
78013                         /*questionOrExclamationToken*/ undefined, 
78014                         /*type*/ undefined, 
78015                         /*initializer*/ undefined)), parameter));
78016                     }
78017                 }
78018             }
78019             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78020             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78021         }
78022         /**
78023          * Gets either the static or instance members of a class that are decorated, or have
78024          * parameters that are decorated.
78025          *
78026          * @param node The class containing the member.
78027          * @param isStatic A value indicating whether to retrieve static or instance members of
78028          *                 the class.
78029          */
78030         function getDecoratedClassElements(node, isStatic) {
78031             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78032         }
78033         /**
78034          * Determines whether a class member is a static member of a class that is decorated, or
78035          * has parameters that are decorated.
78036          *
78037          * @param member The class member.
78038          */
78039         function isStaticDecoratedClassElement(member, parent) {
78040             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78041         }
78042         /**
78043          * Determines whether a class member is an instance member of a class that is decorated,
78044          * or has parameters that are decorated.
78045          *
78046          * @param member The class member.
78047          */
78048         function isInstanceDecoratedClassElement(member, parent) {
78049             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78050         }
78051         /**
78052          * Determines whether a class member is either a static or an instance member of a class
78053          * that is decorated, or has parameters that are decorated.
78054          *
78055          * @param member The class member.
78056          */
78057         function isDecoratedClassElement(member, isStatic, parent) {
78058             return ts.nodeOrChildIsDecorated(member, parent)
78059                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78060         }
78061         /**
78062          * Gets an array of arrays of decorators for the parameters of a function-like node.
78063          * The offset into the result array should correspond to the offset of the parameter.
78064          *
78065          * @param node The function-like node.
78066          */
78067         function getDecoratorsOfParameters(node) {
78068             var decorators;
78069             if (node) {
78070                 var parameters = node.parameters;
78071                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78072                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78073                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78074                 for (var i = 0; i < numParameters; i++) {
78075                     var parameter = parameters[i + firstParameterOffset];
78076                     if (decorators || parameter.decorators) {
78077                         if (!decorators) {
78078                             decorators = new Array(numParameters);
78079                         }
78080                         decorators[i] = parameter.decorators;
78081                     }
78082                 }
78083             }
78084             return decorators;
78085         }
78086         /**
78087          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78088          * parameters of the constructor of the class.
78089          *
78090          * @param node The class node.
78091          */
78092         function getAllDecoratorsOfConstructor(node) {
78093             var decorators = node.decorators;
78094             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78095             if (!decorators && !parameters) {
78096                 return undefined;
78097             }
78098             return {
78099                 decorators: decorators,
78100                 parameters: parameters
78101             };
78102         }
78103         /**
78104          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78105          *
78106          * @param node The class node that contains the member.
78107          * @param member The class member.
78108          */
78109         function getAllDecoratorsOfClassElement(node, member) {
78110             switch (member.kind) {
78111                 case 163 /* GetAccessor */:
78112                 case 164 /* SetAccessor */:
78113                     return getAllDecoratorsOfAccessors(node, member);
78114                 case 161 /* MethodDeclaration */:
78115                     return getAllDecoratorsOfMethod(member);
78116                 case 159 /* PropertyDeclaration */:
78117                     return getAllDecoratorsOfProperty(member);
78118                 default:
78119                     return undefined;
78120             }
78121         }
78122         /**
78123          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78124          *
78125          * @param node The class node that contains the accessor.
78126          * @param accessor The class accessor member.
78127          */
78128         function getAllDecoratorsOfAccessors(node, accessor) {
78129             if (!accessor.body) {
78130                 return undefined;
78131             }
78132             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78133             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78134             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78135                 return undefined;
78136             }
78137             var decorators = firstAccessorWithDecorators.decorators;
78138             var parameters = getDecoratorsOfParameters(setAccessor);
78139             if (!decorators && !parameters) {
78140                 return undefined;
78141             }
78142             return { decorators: decorators, parameters: parameters };
78143         }
78144         /**
78145          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78146          *
78147          * @param method The class method member.
78148          */
78149         function getAllDecoratorsOfMethod(method) {
78150             if (!method.body) {
78151                 return undefined;
78152             }
78153             var decorators = method.decorators;
78154             var parameters = getDecoratorsOfParameters(method);
78155             if (!decorators && !parameters) {
78156                 return undefined;
78157             }
78158             return { decorators: decorators, parameters: parameters };
78159         }
78160         /**
78161          * Gets an AllDecorators object containing the decorators for the property.
78162          *
78163          * @param property The class property member.
78164          */
78165         function getAllDecoratorsOfProperty(property) {
78166             var decorators = property.decorators;
78167             if (!decorators) {
78168                 return undefined;
78169             }
78170             return { decorators: decorators };
78171         }
78172         /**
78173          * Transforms all of the decorators for a declaration into an array of expressions.
78174          *
78175          * @param node The declaration node.
78176          * @param allDecorators An object containing all of the decorators for the declaration.
78177          */
78178         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78179             if (!allDecorators) {
78180                 return undefined;
78181             }
78182             var decoratorExpressions = [];
78183             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78184             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78185             addTypeMetadata(node, container, decoratorExpressions);
78186             return decoratorExpressions;
78187         }
78188         /**
78189          * Generates statements used to apply decorators to either the static or instance members
78190          * of a class.
78191          *
78192          * @param node The class node.
78193          * @param isStatic A value indicating whether to generate statements for static or
78194          *                 instance members.
78195          */
78196         function addClassElementDecorationStatements(statements, node, isStatic) {
78197             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78198         }
78199         /**
78200          * Generates expressions used to apply decorators to either the static or instance members
78201          * of a class.
78202          *
78203          * @param node The class node.
78204          * @param isStatic A value indicating whether to generate expressions for static or
78205          *                 instance members.
78206          */
78207         function generateClassElementDecorationExpressions(node, isStatic) {
78208             var members = getDecoratedClassElements(node, isStatic);
78209             var expressions;
78210             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78211                 var member = members_6[_i];
78212                 var expression = generateClassElementDecorationExpression(node, member);
78213                 if (expression) {
78214                     if (!expressions) {
78215                         expressions = [expression];
78216                     }
78217                     else {
78218                         expressions.push(expression);
78219                     }
78220                 }
78221             }
78222             return expressions;
78223         }
78224         /**
78225          * Generates an expression used to evaluate class element decorators at runtime.
78226          *
78227          * @param node The class node that contains the member.
78228          * @param member The class member.
78229          */
78230         function generateClassElementDecorationExpression(node, member) {
78231             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78232             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78233             if (!decoratorExpressions) {
78234                 return undefined;
78235             }
78236             // Emit the call to __decorate. Given the following:
78237             //
78238             //   class C {
78239             //     @dec method(@dec2 x) {}
78240             //     @dec get accessor() {}
78241             //     @dec prop;
78242             //   }
78243             //
78244             // The emit for a method is:
78245             //
78246             //   __decorate([
78247             //       dec,
78248             //       __param(0, dec2),
78249             //       __metadata("design:type", Function),
78250             //       __metadata("design:paramtypes", [Object]),
78251             //       __metadata("design:returntype", void 0)
78252             //   ], C.prototype, "method", null);
78253             //
78254             // The emit for an accessor is:
78255             //
78256             //   __decorate([
78257             //       dec
78258             //   ], C.prototype, "accessor", null);
78259             //
78260             // The emit for a property is:
78261             //
78262             //   __decorate([
78263             //       dec
78264             //   ], C.prototype, "prop");
78265             //
78266             var prefix = getClassMemberPrefix(node, member);
78267             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78268             var descriptor = languageVersion > 0 /* ES3 */
78269                 ? member.kind === 159 /* PropertyDeclaration */
78270                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78271                     // should not invoke `Object.getOwnPropertyDescriptor`.
78272                     ? ts.createVoidZero()
78273                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78274                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78275                     : ts.createNull()
78276                 : undefined;
78277             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78278             ts.setEmitFlags(helper, 1536 /* NoComments */);
78279             return helper;
78280         }
78281         /**
78282          * Generates a __decorate helper call for a class constructor.
78283          *
78284          * @param node The class node.
78285          */
78286         function addConstructorDecorationStatement(statements, node) {
78287             var expression = generateConstructorDecorationExpression(node);
78288             if (expression) {
78289                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78290             }
78291         }
78292         /**
78293          * Generates a __decorate helper call for a class constructor.
78294          *
78295          * @param node The class node.
78296          */
78297         function generateConstructorDecorationExpression(node) {
78298             var allDecorators = getAllDecoratorsOfConstructor(node);
78299             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78300             if (!decoratorExpressions) {
78301                 return undefined;
78302             }
78303             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78304             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78305             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78306             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78307             ts.setEmitFlags(expression, 1536 /* NoComments */);
78308             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78309             return expression;
78310         }
78311         /**
78312          * Transforms a decorator into an expression.
78313          *
78314          * @param decorator The decorator node.
78315          */
78316         function transformDecorator(decorator) {
78317             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78318         }
78319         /**
78320          * Transforms the decorators of a parameter.
78321          *
78322          * @param decorators The decorators for the parameter at the provided offset.
78323          * @param parameterOffset The offset of the parameter.
78324          */
78325         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78326             var expressions;
78327             if (decorators) {
78328                 expressions = [];
78329                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78330                     var decorator = decorators_1[_i];
78331                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78332                     /*location*/ decorator.expression);
78333                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78334                     expressions.push(helper);
78335                 }
78336             }
78337             return expressions;
78338         }
78339         /**
78340          * Adds optional type metadata for a declaration.
78341          *
78342          * @param node The declaration node.
78343          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78344          */
78345         function addTypeMetadata(node, container, decoratorExpressions) {
78346             if (USE_NEW_TYPE_METADATA_FORMAT) {
78347                 addNewTypeMetadata(node, container, decoratorExpressions);
78348             }
78349             else {
78350                 addOldTypeMetadata(node, container, decoratorExpressions);
78351             }
78352         }
78353         function addOldTypeMetadata(node, container, decoratorExpressions) {
78354             if (compilerOptions.emitDecoratorMetadata) {
78355                 if (shouldAddTypeMetadata(node)) {
78356                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78357                 }
78358                 if (shouldAddParamTypesMetadata(node)) {
78359                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78360                 }
78361                 if (shouldAddReturnTypeMetadata(node)) {
78362                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78363                 }
78364             }
78365         }
78366         function addNewTypeMetadata(node, container, decoratorExpressions) {
78367             if (compilerOptions.emitDecoratorMetadata) {
78368                 var properties = void 0;
78369                 if (shouldAddTypeMetadata(node)) {
78370                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78371                 }
78372                 if (shouldAddParamTypesMetadata(node)) {
78373                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78374                 }
78375                 if (shouldAddReturnTypeMetadata(node)) {
78376                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78377                 }
78378                 if (properties) {
78379                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78380                 }
78381             }
78382         }
78383         /**
78384          * Determines whether to emit the "design:type" metadata based on the node's kind.
78385          * The caller should have already tested whether the node has decorators and whether the
78386          * emitDecoratorMetadata compiler option is set.
78387          *
78388          * @param node The node to test.
78389          */
78390         function shouldAddTypeMetadata(node) {
78391             var kind = node.kind;
78392             return kind === 161 /* MethodDeclaration */
78393                 || kind === 163 /* GetAccessor */
78394                 || kind === 164 /* SetAccessor */
78395                 || kind === 159 /* PropertyDeclaration */;
78396         }
78397         /**
78398          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78399          * The caller should have already tested whether the node has decorators and whether the
78400          * emitDecoratorMetadata compiler option is set.
78401          *
78402          * @param node The node to test.
78403          */
78404         function shouldAddReturnTypeMetadata(node) {
78405             return node.kind === 161 /* MethodDeclaration */;
78406         }
78407         /**
78408          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78409          * The caller should have already tested whether the node has decorators and whether the
78410          * emitDecoratorMetadata compiler option is set.
78411          *
78412          * @param node The node to test.
78413          */
78414         function shouldAddParamTypesMetadata(node) {
78415             switch (node.kind) {
78416                 case 245 /* ClassDeclaration */:
78417                 case 214 /* ClassExpression */:
78418                     return ts.getFirstConstructorWithBody(node) !== undefined;
78419                 case 161 /* MethodDeclaration */:
78420                 case 163 /* GetAccessor */:
78421                 case 164 /* SetAccessor */:
78422                     return true;
78423             }
78424             return false;
78425         }
78426         function getAccessorTypeNode(node) {
78427             var accessors = resolver.getAllAccessorDeclarations(node);
78428             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78429                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78430         }
78431         /**
78432          * Serializes the type of a node for use with decorator type metadata.
78433          *
78434          * @param node The node that should have its type serialized.
78435          */
78436         function serializeTypeOfNode(node) {
78437             switch (node.kind) {
78438                 case 159 /* PropertyDeclaration */:
78439                 case 156 /* Parameter */:
78440                     return serializeTypeNode(node.type);
78441                 case 164 /* SetAccessor */:
78442                 case 163 /* GetAccessor */:
78443                     return serializeTypeNode(getAccessorTypeNode(node));
78444                 case 245 /* ClassDeclaration */:
78445                 case 214 /* ClassExpression */:
78446                 case 161 /* MethodDeclaration */:
78447                     return ts.createIdentifier("Function");
78448                 default:
78449                     return ts.createVoidZero();
78450             }
78451         }
78452         /**
78453          * Serializes the types of the parameters of a node for use with decorator type metadata.
78454          *
78455          * @param node The node that should have its parameter types serialized.
78456          */
78457         function serializeParameterTypesOfNode(node, container) {
78458             var valueDeclaration = ts.isClassLike(node)
78459                 ? ts.getFirstConstructorWithBody(node)
78460                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78461                     ? node
78462                     : undefined;
78463             var expressions = [];
78464             if (valueDeclaration) {
78465                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78466                 var numParameters = parameters.length;
78467                 for (var i = 0; i < numParameters; i++) {
78468                     var parameter = parameters[i];
78469                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78470                         continue;
78471                     }
78472                     if (parameter.dotDotDotToken) {
78473                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78474                     }
78475                     else {
78476                         expressions.push(serializeTypeOfNode(parameter));
78477                     }
78478                 }
78479             }
78480             return ts.createArrayLiteral(expressions);
78481         }
78482         function getParametersOfDecoratedDeclaration(node, container) {
78483             if (container && node.kind === 163 /* GetAccessor */) {
78484                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78485                 if (setAccessor) {
78486                     return setAccessor.parameters;
78487                 }
78488             }
78489             return node.parameters;
78490         }
78491         /**
78492          * Serializes the return type of a node for use with decorator type metadata.
78493          *
78494          * @param node The node that should have its return type serialized.
78495          */
78496         function serializeReturnTypeOfNode(node) {
78497             if (ts.isFunctionLike(node) && node.type) {
78498                 return serializeTypeNode(node.type);
78499             }
78500             else if (ts.isAsyncFunction(node)) {
78501                 return ts.createIdentifier("Promise");
78502             }
78503             return ts.createVoidZero();
78504         }
78505         /**
78506          * Serializes a type node for use with decorator type metadata.
78507          *
78508          * Types are serialized in the following fashion:
78509          * - Void types point to "undefined" (e.g. "void 0")
78510          * - Function and Constructor types point to the global "Function" constructor.
78511          * - Interface types with a call or construct signature types point to the global
78512          *   "Function" constructor.
78513          * - Array and Tuple types point to the global "Array" constructor.
78514          * - Type predicates and booleans point to the global "Boolean" constructor.
78515          * - String literal types and strings point to the global "String" constructor.
78516          * - Enum and number types point to the global "Number" constructor.
78517          * - Symbol types point to the global "Symbol" constructor.
78518          * - Type references to classes (or class-like variables) point to the constructor for the class.
78519          * - Anything else points to the global "Object" constructor.
78520          *
78521          * @param node The type node to serialize.
78522          */
78523         function serializeTypeNode(node) {
78524             if (node === undefined) {
78525                 return ts.createIdentifier("Object");
78526             }
78527             switch (node.kind) {
78528                 case 110 /* VoidKeyword */:
78529                 case 146 /* UndefinedKeyword */:
78530                 case 100 /* NullKeyword */:
78531                 case 137 /* NeverKeyword */:
78532                     return ts.createVoidZero();
78533                 case 182 /* ParenthesizedType */:
78534                     return serializeTypeNode(node.type);
78535                 case 170 /* FunctionType */:
78536                 case 171 /* ConstructorType */:
78537                     return ts.createIdentifier("Function");
78538                 case 174 /* ArrayType */:
78539                 case 175 /* TupleType */:
78540                     return ts.createIdentifier("Array");
78541                 case 168 /* TypePredicate */:
78542                 case 128 /* BooleanKeyword */:
78543                     return ts.createIdentifier("Boolean");
78544                 case 143 /* StringKeyword */:
78545                     return ts.createIdentifier("String");
78546                 case 141 /* ObjectKeyword */:
78547                     return ts.createIdentifier("Object");
78548                 case 187 /* LiteralType */:
78549                     switch (node.literal.kind) {
78550                         case 10 /* StringLiteral */:
78551                             return ts.createIdentifier("String");
78552                         case 207 /* PrefixUnaryExpression */:
78553                         case 8 /* NumericLiteral */:
78554                             return ts.createIdentifier("Number");
78555                         case 9 /* BigIntLiteral */:
78556                             return getGlobalBigIntNameWithFallback();
78557                         case 106 /* TrueKeyword */:
78558                         case 91 /* FalseKeyword */:
78559                             return ts.createIdentifier("Boolean");
78560                         default:
78561                             return ts.Debug.failBadSyntaxKind(node.literal);
78562                     }
78563                 case 140 /* NumberKeyword */:
78564                     return ts.createIdentifier("Number");
78565                 case 151 /* BigIntKeyword */:
78566                     return getGlobalBigIntNameWithFallback();
78567                 case 144 /* SymbolKeyword */:
78568                     return languageVersion < 2 /* ES2015 */
78569                         ? getGlobalSymbolNameWithFallback()
78570                         : ts.createIdentifier("Symbol");
78571                 case 169 /* TypeReference */:
78572                     return serializeTypeReferenceNode(node);
78573                 case 179 /* IntersectionType */:
78574                 case 178 /* UnionType */:
78575                     return serializeTypeList(node.types);
78576                 case 180 /* ConditionalType */:
78577                     return serializeTypeList([node.trueType, node.falseType]);
78578                 case 184 /* TypeOperator */:
78579                     if (node.operator === 138 /* ReadonlyKeyword */) {
78580                         return serializeTypeNode(node.type);
78581                     }
78582                     break;
78583                 case 172 /* TypeQuery */:
78584                 case 185 /* IndexedAccessType */:
78585                 case 186 /* MappedType */:
78586                 case 173 /* TypeLiteral */:
78587                 case 125 /* AnyKeyword */:
78588                 case 148 /* UnknownKeyword */:
78589                 case 183 /* ThisType */:
78590                 case 188 /* ImportType */:
78591                     break;
78592                 // handle JSDoc types from an invalid parse
78593                 case 295 /* JSDocAllType */:
78594                 case 296 /* JSDocUnknownType */:
78595                 case 300 /* JSDocFunctionType */:
78596                 case 301 /* JSDocVariadicType */:
78597                 case 302 /* JSDocNamepathType */:
78598                     break;
78599                 case 297 /* JSDocNullableType */:
78600                 case 298 /* JSDocNonNullableType */:
78601                 case 299 /* JSDocOptionalType */:
78602                     return serializeTypeNode(node.type);
78603                 default:
78604                     return ts.Debug.failBadSyntaxKind(node);
78605             }
78606             return ts.createIdentifier("Object");
78607         }
78608         function serializeTypeList(types) {
78609             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78610             // so that aliases can be marked as referenced
78611             var serializedUnion;
78612             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78613                 var typeNode = types_21[_i];
78614                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78615                     typeNode = typeNode.type; // Skip parens if need be
78616                 }
78617                 if (typeNode.kind === 137 /* NeverKeyword */) {
78618                     continue; // Always elide `never` from the union/intersection if possible
78619                 }
78620                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78621                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78622                 }
78623                 var serializedIndividual = serializeTypeNode(typeNode);
78624                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78625                     // One of the individual is global object, return immediately
78626                     return serializedIndividual;
78627                 }
78628                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78629                 // anything more complex and we will just default to Object
78630                 else if (serializedUnion) {
78631                     // Different types
78632                     if (!ts.isIdentifier(serializedUnion) ||
78633                         !ts.isIdentifier(serializedIndividual) ||
78634                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78635                         return ts.createIdentifier("Object");
78636                     }
78637                 }
78638                 else {
78639                     // Initialize the union type
78640                     serializedUnion = serializedIndividual;
78641                 }
78642             }
78643             // If we were able to find common type, use it
78644             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78645         }
78646         /**
78647          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78648          * decorator type metadata.
78649          *
78650          * @param node The type reference node.
78651          */
78652         function serializeTypeReferenceNode(node) {
78653             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78654             switch (kind) {
78655                 case ts.TypeReferenceSerializationKind.Unknown:
78656                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78657                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78658                         return ts.createIdentifier("Object");
78659                     }
78660                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78661                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78662                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78663                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78664                     return serializeEntityNameAsExpression(node.typeName);
78665                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78666                     return ts.createVoidZero();
78667                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78668                     return getGlobalBigIntNameWithFallback();
78669                 case ts.TypeReferenceSerializationKind.BooleanType:
78670                     return ts.createIdentifier("Boolean");
78671                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78672                     return ts.createIdentifier("Number");
78673                 case ts.TypeReferenceSerializationKind.StringLikeType:
78674                     return ts.createIdentifier("String");
78675                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78676                     return ts.createIdentifier("Array");
78677                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78678                     return languageVersion < 2 /* ES2015 */
78679                         ? getGlobalSymbolNameWithFallback()
78680                         : ts.createIdentifier("Symbol");
78681                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78682                     return ts.createIdentifier("Function");
78683                 case ts.TypeReferenceSerializationKind.Promise:
78684                     return ts.createIdentifier("Promise");
78685                 case ts.TypeReferenceSerializationKind.ObjectType:
78686                     return ts.createIdentifier("Object");
78687                 default:
78688                     return ts.Debug.assertNever(kind);
78689             }
78690         }
78691         function createCheckedValue(left, right) {
78692             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78693         }
78694         /**
78695          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78696          *
78697          * @param node The entity name to serialize.
78698          */
78699         function serializeEntityNameAsExpressionFallback(node) {
78700             if (node.kind === 75 /* Identifier */) {
78701                 // A -> typeof A !== undefined && A
78702                 var copied = serializeEntityNameAsExpression(node);
78703                 return createCheckedValue(copied, copied);
78704             }
78705             if (node.left.kind === 75 /* Identifier */) {
78706                 // A.B -> typeof A !== undefined && A.B
78707                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78708             }
78709             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78710             var left = serializeEntityNameAsExpressionFallback(node.left);
78711             var temp = ts.createTempVariable(hoistVariableDeclaration);
78712             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78713         }
78714         /**
78715          * Serializes an entity name as an expression for decorator type metadata.
78716          *
78717          * @param node The entity name to serialize.
78718          */
78719         function serializeEntityNameAsExpression(node) {
78720             switch (node.kind) {
78721                 case 75 /* Identifier */:
78722                     // Create a clone of the name with a new parent, and treat it as if it were
78723                     // a source tree node for the purposes of the checker.
78724                     var name = ts.getMutableClone(node);
78725                     name.flags &= ~8 /* Synthesized */;
78726                     name.original = undefined;
78727                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78728                     return name;
78729                 case 153 /* QualifiedName */:
78730                     return serializeQualifiedNameAsExpression(node);
78731             }
78732         }
78733         /**
78734          * Serializes an qualified name as an expression for decorator type metadata.
78735          *
78736          * @param node The qualified name to serialize.
78737          * @param useFallback A value indicating whether to use logical operators to test for the
78738          *                    qualified name at runtime.
78739          */
78740         function serializeQualifiedNameAsExpression(node) {
78741             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78742         }
78743         /**
78744          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78745          * available.
78746          */
78747         function getGlobalSymbolNameWithFallback() {
78748             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78749         }
78750         /**
78751          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78752          * available.
78753          */
78754         function getGlobalBigIntNameWithFallback() {
78755             return languageVersion < 99 /* ESNext */
78756                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78757                 : ts.createIdentifier("BigInt");
78758         }
78759         /**
78760          * Gets an expression that represents a property name (for decorated properties or enums).
78761          * For a computed property, a name is generated for the node.
78762          *
78763          * @param member The member whose name should be converted into an expression.
78764          */
78765         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78766             var name = member.name;
78767             if (ts.isPrivateIdentifier(name)) {
78768                 return ts.createIdentifier("");
78769             }
78770             else if (ts.isComputedPropertyName(name)) {
78771                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78772                     ? ts.getGeneratedNameForNode(name)
78773                     : name.expression;
78774             }
78775             else if (ts.isIdentifier(name)) {
78776                 return ts.createLiteral(ts.idText(name));
78777             }
78778             else {
78779                 return ts.getSynthesizedClone(name);
78780             }
78781         }
78782         /**
78783          * Visits the property name of a class element, for use when emitting property
78784          * initializers. For a computed property on a node with decorators, a temporary
78785          * value is stored for later use.
78786          *
78787          * @param member The member whose name should be visited.
78788          */
78789         function visitPropertyNameOfClassElement(member) {
78790             var name = member.name;
78791             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78792             // The names are used more than once when:
78793             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78794             //   - the property has a decorator.
78795             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78796                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78797                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78798                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78799                     var generatedName = ts.getGeneratedNameForNode(name);
78800                     hoistVariableDeclaration(generatedName);
78801                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78802                 }
78803             }
78804             return ts.visitNode(name, visitor, ts.isPropertyName);
78805         }
78806         /**
78807          * Transforms a HeritageClause with TypeScript syntax.
78808          *
78809          * This function will only be called when one of the following conditions are met:
78810          * - The node is a non-`extends` heritage clause that should be elided.
78811          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78812          *
78813          * @param node The HeritageClause to transform.
78814          */
78815         function visitHeritageClause(node) {
78816             if (node.token === 113 /* ImplementsKeyword */) {
78817                 // implements clauses are elided
78818                 return undefined;
78819             }
78820             return ts.visitEachChild(node, visitor, context);
78821         }
78822         /**
78823          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
78824          *
78825          * This function will only be called when one of the following conditions are met:
78826          * - The node contains type arguments that should be elided.
78827          *
78828          * @param node The ExpressionWithTypeArguments to transform.
78829          */
78830         function visitExpressionWithTypeArguments(node) {
78831             return ts.updateExpressionWithTypeArguments(node, 
78832             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
78833         }
78834         /**
78835          * Determines whether to emit a function-like declaration. We should not emit the
78836          * declaration if it does not have a body.
78837          *
78838          * @param node The declaration node.
78839          */
78840         function shouldEmitFunctionLikeDeclaration(node) {
78841             return !ts.nodeIsMissing(node.body);
78842         }
78843         function visitPropertyDeclaration(node) {
78844             if (node.flags & 8388608 /* Ambient */) {
78845                 return undefined;
78846             }
78847             var updated = ts.updateProperty(node, 
78848             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
78849             /*questionOrExclamationToken*/ undefined, 
78850             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
78851             if (updated !== node) {
78852                 // While we emit the source map for the node after skipping decorators and modifiers,
78853                 // we need to emit the comments for the original range.
78854                 ts.setCommentRange(updated, node);
78855                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78856             }
78857             return updated;
78858         }
78859         function visitConstructor(node) {
78860             if (!shouldEmitFunctionLikeDeclaration(node)) {
78861                 return undefined;
78862             }
78863             return ts.updateConstructor(node, 
78864             /*decorators*/ undefined, 
78865             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
78866         }
78867         function transformConstructorBody(body, constructor) {
78868             var parametersWithPropertyAssignments = constructor &&
78869                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78870             if (!ts.some(parametersWithPropertyAssignments)) {
78871                 return ts.visitFunctionBody(body, visitor, context);
78872             }
78873             var statements = [];
78874             var indexOfFirstStatement = 0;
78875             resumeLexicalEnvironment();
78876             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
78877             // Add parameters with property assignments. Transforms this:
78878             //
78879             //  constructor (public x, public y) {
78880             //  }
78881             //
78882             // Into this:
78883             //
78884             //  constructor (x, y) {
78885             //      this.x = x;
78886             //      this.y = y;
78887             //  }
78888             //
78889             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
78890             // Add the existing statements, skipping the initial super call.
78891             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
78892             // End the lexical environment.
78893             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
78894             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
78895             ts.setTextRange(block, /*location*/ body);
78896             ts.setOriginalNode(block, body);
78897             return block;
78898         }
78899         /**
78900          * Transforms a parameter into a property assignment statement.
78901          *
78902          * @param node The parameter declaration.
78903          */
78904         function transformParameterWithPropertyAssignment(node) {
78905             var name = node.name;
78906             if (!ts.isIdentifier(name)) {
78907                 return undefined;
78908             }
78909             var propertyName = ts.getMutableClone(name);
78910             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
78911             var localName = ts.getMutableClone(name);
78912             ts.setEmitFlags(localName, 1536 /* NoComments */);
78913             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))));
78914         }
78915         function visitMethodDeclaration(node) {
78916             if (!shouldEmitFunctionLikeDeclaration(node)) {
78917                 return undefined;
78918             }
78919             var updated = ts.updateMethod(node, 
78920             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
78921             /*questionToken*/ undefined, 
78922             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78923             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
78924             if (updated !== node) {
78925                 // While we emit the source map for the node after skipping decorators and modifiers,
78926                 // we need to emit the comments for the original range.
78927                 ts.setCommentRange(updated, node);
78928                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78929             }
78930             return updated;
78931         }
78932         /**
78933          * Determines whether to emit an accessor declaration. We should not emit the
78934          * declaration if it does not have a body and is abstract.
78935          *
78936          * @param node The declaration node.
78937          */
78938         function shouldEmitAccessorDeclaration(node) {
78939             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
78940         }
78941         function visitGetAccessor(node) {
78942             if (!shouldEmitAccessorDeclaration(node)) {
78943                 return undefined;
78944             }
78945             var updated = ts.updateGetAccessor(node, 
78946             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
78947             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78948             if (updated !== node) {
78949                 // While we emit the source map for the node after skipping decorators and modifiers,
78950                 // we need to emit the comments for the original range.
78951                 ts.setCommentRange(updated, node);
78952                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78953             }
78954             return updated;
78955         }
78956         function visitSetAccessor(node) {
78957             if (!shouldEmitAccessorDeclaration(node)) {
78958                 return undefined;
78959             }
78960             var updated = ts.updateSetAccessor(node, 
78961             /*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([]));
78962             if (updated !== node) {
78963                 // While we emit the source map for the node after skipping decorators and modifiers,
78964                 // we need to emit the comments for the original range.
78965                 ts.setCommentRange(updated, node);
78966                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78967             }
78968             return updated;
78969         }
78970         function visitFunctionDeclaration(node) {
78971             if (!shouldEmitFunctionLikeDeclaration(node)) {
78972                 return ts.createNotEmittedStatement(node);
78973             }
78974             var updated = ts.updateFunctionDeclaration(node, 
78975             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
78976             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78977             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78978             if (isExportOfNamespace(node)) {
78979                 var statements = [updated];
78980                 addExportMemberAssignment(statements, node);
78981                 return statements;
78982             }
78983             return updated;
78984         }
78985         function visitFunctionExpression(node) {
78986             if (!shouldEmitFunctionLikeDeclaration(node)) {
78987                 return ts.createOmittedExpression();
78988             }
78989             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
78990             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78991             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78992             return updated;
78993         }
78994         function visitArrowFunction(node) {
78995             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
78996             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78997             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
78998             return updated;
78999         }
79000         function visitParameter(node) {
79001             if (ts.parameterIsThisKeyword(node)) {
79002                 return undefined;
79003             }
79004             var updated = ts.updateParameter(node, 
79005             /*decorators*/ undefined, 
79006             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79007             /*questionToken*/ undefined, 
79008             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79009             if (updated !== node) {
79010                 // While we emit the source map for the node after skipping decorators and modifiers,
79011                 // we need to emit the comments for the original range.
79012                 ts.setCommentRange(updated, node);
79013                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79014                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79015                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79016             }
79017             return updated;
79018         }
79019         function visitVariableStatement(node) {
79020             if (isExportOfNamespace(node)) {
79021                 var variables = ts.getInitializedVariables(node.declarationList);
79022                 if (variables.length === 0) {
79023                     // elide statement if there are no initialized variables.
79024                     return undefined;
79025                 }
79026                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79027             }
79028             else {
79029                 return ts.visitEachChild(node, visitor, context);
79030             }
79031         }
79032         function transformInitializedVariable(node) {
79033             var name = node.name;
79034             if (ts.isBindingPattern(name)) {
79035                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79036                 /*needsValue*/ false, createNamespaceExportExpression);
79037             }
79038             else {
79039                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79040                 /*location*/ node);
79041             }
79042         }
79043         function visitVariableDeclaration(node) {
79044             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79045             /*exclaimationToken*/ undefined, 
79046             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79047         }
79048         function visitParenthesizedExpression(node) {
79049             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79050             if (ts.isAssertionExpression(innerExpression)) {
79051                 // Make sure we consider all nested cast expressions, e.g.:
79052                 // (<any><number><any>-A).x;
79053                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79054                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79055                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79056                 // the parentheses, however, could cause change in the semantics of the generated
79057                 // code if the casted expression has a lower precedence than the rest of the
79058                 // expression.
79059                 //
79060                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79061                 // preserve the position information of the original expression.
79062                 //
79063                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79064                 // we can safely elide the parentheses here, as a new synthetic
79065                 // ParenthesizedExpression will be inserted if we remove parentheses too
79066                 // aggressively.
79067                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79068                 // correctly for return and throw, we must keep the parenthesis
79069                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79070                     return ts.updateParen(node, expression);
79071                 }
79072                 return ts.createPartiallyEmittedExpression(expression, node);
79073             }
79074             return ts.visitEachChild(node, visitor, context);
79075         }
79076         function visitAssertionExpression(node) {
79077             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79078             return ts.createPartiallyEmittedExpression(expression, node);
79079         }
79080         function visitNonNullExpression(node) {
79081             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79082             return ts.createPartiallyEmittedExpression(expression, node);
79083         }
79084         function visitCallExpression(node) {
79085             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79086             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79087         }
79088         function visitNewExpression(node) {
79089             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79090             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79091         }
79092         function visitTaggedTemplateExpression(node) {
79093             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79094             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79095         }
79096         function visitJsxSelfClosingElement(node) {
79097             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79098             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79099         }
79100         function visitJsxJsxOpeningElement(node) {
79101             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79102             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79103         }
79104         /**
79105          * Determines whether to emit an enum declaration.
79106          *
79107          * @param node The enum declaration node.
79108          */
79109         function shouldEmitEnumDeclaration(node) {
79110             return !ts.isEnumConst(node)
79111                 || compilerOptions.preserveConstEnums
79112                 || compilerOptions.isolatedModules;
79113         }
79114         /**
79115          * Visits an enum declaration.
79116          *
79117          * This function will be called any time a TypeScript enum is encountered.
79118          *
79119          * @param node The enum declaration node.
79120          */
79121         function visitEnumDeclaration(node) {
79122             if (!shouldEmitEnumDeclaration(node)) {
79123                 return ts.createNotEmittedStatement(node);
79124             }
79125             var statements = [];
79126             // We request to be advised when the printer is about to print this node. This allows
79127             // us to set up the correct state for later substitutions.
79128             var emitFlags = 2 /* AdviseOnEmitNode */;
79129             // If needed, we should emit a variable declaration for the enum. If we emit
79130             // a leading variable declaration, we should not emit leading comments for the
79131             // enum body.
79132             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79133             if (varAdded) {
79134                 // We should still emit the comments if we are emitting a system module.
79135                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79136                     emitFlags |= 512 /* NoLeadingComments */;
79137                 }
79138             }
79139             // `parameterName` is the declaration name used inside of the enum.
79140             var parameterName = getNamespaceParameterName(node);
79141             // `containerName` is the expression used inside of the enum for assignments.
79142             var containerName = getNamespaceContainerName(node);
79143             // `exportName` is the expression used within this node's container for any exported references.
79144             var exportName = ts.hasModifier(node, 1 /* Export */)
79145                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79146                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79147             //  x || (x = {})
79148             //  exports.x || (exports.x = {})
79149             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79150             if (hasNamespaceQualifiedExportName(node)) {
79151                 // `localName` is the expression used within this node's containing scope for any local references.
79152                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79153                 //  x = (exports.x || (exports.x = {}))
79154                 moduleArg = ts.createAssignment(localName, moduleArg);
79155             }
79156             //  (function (x) {
79157             //      x[x["y"] = 0] = "y";
79158             //      ...
79159             //  })(x || (x = {}));
79160             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79161             /*modifiers*/ undefined, 
79162             /*asteriskToken*/ undefined, 
79163             /*name*/ undefined, 
79164             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79165             /*type*/ undefined, transformEnumBody(node, containerName)), 
79166             /*typeArguments*/ undefined, [moduleArg]));
79167             ts.setOriginalNode(enumStatement, node);
79168             if (varAdded) {
79169                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79170                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79171                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79172             }
79173             ts.setTextRange(enumStatement, node);
79174             ts.addEmitFlags(enumStatement, emitFlags);
79175             statements.push(enumStatement);
79176             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79177             // the end of the declaration.
79178             statements.push(ts.createEndOfDeclarationMarker(node));
79179             return statements;
79180         }
79181         /**
79182          * Transforms the body of an enum declaration.
79183          *
79184          * @param node The enum declaration node.
79185          */
79186         function transformEnumBody(node, localName) {
79187             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79188             currentNamespaceContainerName = localName;
79189             var statements = [];
79190             startLexicalEnvironment();
79191             var members = ts.map(node.members, transformEnumMember);
79192             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79193             ts.addRange(statements, members);
79194             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79195             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79196             /*multiLine*/ true);
79197         }
79198         /**
79199          * Transforms an enum member into a statement.
79200          *
79201          * @param member The enum member node.
79202          */
79203         function transformEnumMember(member) {
79204             // enums don't support computed properties
79205             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79206             // old emitter always generate 'expression' part of the name as-is.
79207             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79208             var valueExpression = transformEnumMemberDeclarationValue(member);
79209             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79210             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79211                 innerAssignment :
79212                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79213             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79214         }
79215         /**
79216          * Transforms the value of an enum member.
79217          *
79218          * @param member The enum member node.
79219          */
79220         function transformEnumMemberDeclarationValue(member) {
79221             var value = resolver.getConstantValue(member);
79222             if (value !== undefined) {
79223                 return ts.createLiteral(value);
79224             }
79225             else {
79226                 enableSubstitutionForNonQualifiedEnumMembers();
79227                 if (member.initializer) {
79228                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79229                 }
79230                 else {
79231                     return ts.createVoidZero();
79232                 }
79233             }
79234         }
79235         /**
79236          * Determines whether to elide a module declaration.
79237          *
79238          * @param node The module declaration node.
79239          */
79240         function shouldEmitModuleDeclaration(nodeIn) {
79241             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79242             if (!node) {
79243                 // If we can't find a parse tree node, assume the node is instantiated.
79244                 return true;
79245             }
79246             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79247         }
79248         /**
79249          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79250          * or `exports.x`).
79251          */
79252         function hasNamespaceQualifiedExportName(node) {
79253             return isExportOfNamespace(node)
79254                 || (isExternalModuleExport(node)
79255                     && moduleKind !== ts.ModuleKind.ES2015
79256                     && moduleKind !== ts.ModuleKind.ES2020
79257                     && moduleKind !== ts.ModuleKind.ESNext
79258                     && moduleKind !== ts.ModuleKind.System);
79259         }
79260         /**
79261          * Records that a declaration was emitted in the current scope, if it was the first
79262          * declaration for the provided symbol.
79263          */
79264         function recordEmittedDeclarationInScope(node) {
79265             if (!currentScopeFirstDeclarationsOfName) {
79266                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79267             }
79268             var name = declaredNameInScope(node);
79269             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79270                 currentScopeFirstDeclarationsOfName.set(name, node);
79271             }
79272         }
79273         /**
79274          * Determines whether a declaration is the first declaration with
79275          * the same name emitted in the current scope.
79276          */
79277         function isFirstEmittedDeclarationInScope(node) {
79278             if (currentScopeFirstDeclarationsOfName) {
79279                 var name = declaredNameInScope(node);
79280                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79281             }
79282             return true;
79283         }
79284         function declaredNameInScope(node) {
79285             ts.Debug.assertNode(node.name, ts.isIdentifier);
79286             return node.name.escapedText;
79287         }
79288         /**
79289          * Adds a leading VariableStatement for a enum or module declaration.
79290          */
79291         function addVarForEnumOrModuleDeclaration(statements, node) {
79292             // Emit a variable statement for the module. We emit top-level enums as a `var`
79293             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79294             // enums in any other scope are emitted as a `let` declaration.
79295             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79296                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79297             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79298             ts.setOriginalNode(statement, node);
79299             recordEmittedDeclarationInScope(node);
79300             if (isFirstEmittedDeclarationInScope(node)) {
79301                 // Adjust the source map emit to match the old emitter.
79302                 if (node.kind === 248 /* EnumDeclaration */) {
79303                     ts.setSourceMapRange(statement.declarationList, node);
79304                 }
79305                 else {
79306                     ts.setSourceMapRange(statement, node);
79307                 }
79308                 // Trailing comments for module declaration should be emitted after the function closure
79309                 // instead of the variable statement:
79310                 //
79311                 //     /** Module comment*/
79312                 //     module m1 {
79313                 //         function foo4Export() {
79314                 //         }
79315                 //     } // trailing comment module
79316                 //
79317                 // Should emit:
79318                 //
79319                 //     /** Module comment*/
79320                 //     var m1;
79321                 //     (function (m1) {
79322                 //         function foo4Export() {
79323                 //         }
79324                 //     })(m1 || (m1 = {})); // trailing comment module
79325                 //
79326                 ts.setCommentRange(statement, node);
79327                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79328                 statements.push(statement);
79329                 return true;
79330             }
79331             else {
79332                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79333                 // declaration we do not emit a leading variable declaration. To preserve the
79334                 // begin/end semantics of the declararation and to properly handle exports
79335                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79336                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79337                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79338                 statements.push(mergeMarker);
79339                 return false;
79340             }
79341         }
79342         /**
79343          * Visits a module declaration node.
79344          *
79345          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79346          *
79347          * @param node The module declaration node.
79348          */
79349         function visitModuleDeclaration(node) {
79350             if (!shouldEmitModuleDeclaration(node)) {
79351                 return ts.createNotEmittedStatement(node);
79352             }
79353             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79354             enableSubstitutionForNamespaceExports();
79355             var statements = [];
79356             // We request to be advised when the printer is about to print this node. This allows
79357             // us to set up the correct state for later substitutions.
79358             var emitFlags = 2 /* AdviseOnEmitNode */;
79359             // If needed, we should emit a variable declaration for the module. If we emit
79360             // a leading variable declaration, we should not emit leading comments for the
79361             // module body.
79362             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79363             if (varAdded) {
79364                 // We should still emit the comments if we are emitting a system module.
79365                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79366                     emitFlags |= 512 /* NoLeadingComments */;
79367                 }
79368             }
79369             // `parameterName` is the declaration name used inside of the namespace.
79370             var parameterName = getNamespaceParameterName(node);
79371             // `containerName` is the expression used inside of the namespace for exports.
79372             var containerName = getNamespaceContainerName(node);
79373             // `exportName` is the expression used within this node's container for any exported references.
79374             var exportName = ts.hasModifier(node, 1 /* Export */)
79375                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79376                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79377             //  x || (x = {})
79378             //  exports.x || (exports.x = {})
79379             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79380             if (hasNamespaceQualifiedExportName(node)) {
79381                 // `localName` is the expression used within this node's containing scope for any local references.
79382                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79383                 //  x = (exports.x || (exports.x = {}))
79384                 moduleArg = ts.createAssignment(localName, moduleArg);
79385             }
79386             //  (function (x_1) {
79387             //      x_1.y = ...;
79388             //  })(x || (x = {}));
79389             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79390             /*modifiers*/ undefined, 
79391             /*asteriskToken*/ undefined, 
79392             /*name*/ undefined, 
79393             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79394             /*type*/ undefined, transformModuleBody(node, containerName)), 
79395             /*typeArguments*/ undefined, [moduleArg]));
79396             ts.setOriginalNode(moduleStatement, node);
79397             if (varAdded) {
79398                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79399                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79400                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79401             }
79402             ts.setTextRange(moduleStatement, node);
79403             ts.addEmitFlags(moduleStatement, emitFlags);
79404             statements.push(moduleStatement);
79405             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79406             // the end of the declaration.
79407             statements.push(ts.createEndOfDeclarationMarker(node));
79408             return statements;
79409         }
79410         /**
79411          * Transforms the body of a module declaration.
79412          *
79413          * @param node The module declaration node.
79414          */
79415         function transformModuleBody(node, namespaceLocalName) {
79416             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79417             var savedCurrentNamespace = currentNamespace;
79418             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79419             currentNamespaceContainerName = namespaceLocalName;
79420             currentNamespace = node;
79421             currentScopeFirstDeclarationsOfName = undefined;
79422             var statements = [];
79423             startLexicalEnvironment();
79424             var statementsLocation;
79425             var blockLocation;
79426             if (node.body) {
79427                 if (node.body.kind === 250 /* ModuleBlock */) {
79428                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79429                     statementsLocation = node.body.statements;
79430                     blockLocation = node.body;
79431                 }
79432                 else {
79433                     var result = visitModuleDeclaration(node.body);
79434                     if (result) {
79435                         if (ts.isArray(result)) {
79436                             ts.addRange(statements, result);
79437                         }
79438                         else {
79439                             statements.push(result);
79440                         }
79441                     }
79442                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79443                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79444                 }
79445             }
79446             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79447             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79448             currentNamespace = savedCurrentNamespace;
79449             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79450             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79451             /*location*/ statementsLocation), 
79452             /*multiLine*/ true);
79453             ts.setTextRange(block, blockLocation);
79454             // namespace hello.hi.world {
79455             //      function foo() {}
79456             //
79457             //      // TODO, blah
79458             // }
79459             //
79460             // should be emitted as
79461             //
79462             // var hello;
79463             // (function (hello) {
79464             //     var hi;
79465             //     (function (hi) {
79466             //         var world;
79467             //         (function (world) {
79468             //             function foo() { }
79469             //             // TODO, blah
79470             //         })(world = hi.world || (hi.world = {}));
79471             //     })(hi = hello.hi || (hello.hi = {}));
79472             // })(hello || (hello = {}));
79473             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79474             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79475                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79476             }
79477             return block;
79478         }
79479         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79480             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79481                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79482                 return recursiveInnerModule || moduleDeclaration.body;
79483             }
79484         }
79485         /**
79486          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79487          *
79488          * @param node The import declaration node.
79489          */
79490         function visitImportDeclaration(node) {
79491             if (!node.importClause) {
79492                 // Do not elide a side-effect only import declaration.
79493                 //  import "foo";
79494                 return node;
79495             }
79496             if (node.importClause.isTypeOnly) {
79497                 // Always elide type-only imports
79498                 return undefined;
79499             }
79500             // Elide the declaration if the import clause was elided.
79501             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79502             return importClause ||
79503                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79504                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79505                 ? ts.updateImportDeclaration(node, 
79506                 /*decorators*/ undefined, 
79507                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79508                 : undefined;
79509         }
79510         /**
79511          * Visits an import clause, eliding it if it is not referenced.
79512          *
79513          * @param node The import clause node.
79514          */
79515         function visitImportClause(node) {
79516             if (node.isTypeOnly) {
79517                 return undefined;
79518             }
79519             // Elide the import clause if we elide both its name and its named bindings.
79520             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79521             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79522             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79523         }
79524         /**
79525          * Visits named import bindings, eliding it if it is not referenced.
79526          *
79527          * @param node The named import bindings node.
79528          */
79529         function visitNamedImportBindings(node) {
79530             if (node.kind === 256 /* NamespaceImport */) {
79531                 // Elide a namespace import if it is not referenced.
79532                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79533             }
79534             else {
79535                 // Elide named imports if all of its import specifiers are elided.
79536                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79537                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79538             }
79539         }
79540         /**
79541          * Visits an import specifier, eliding it if it is not referenced.
79542          *
79543          * @param node The import specifier node.
79544          */
79545         function visitImportSpecifier(node) {
79546             // Elide an import specifier if it is not referenced.
79547             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79548         }
79549         /**
79550          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79551          * to a value.
79552          *
79553          * @param node The export assignment node.
79554          */
79555         function visitExportAssignment(node) {
79556             // Elide the export assignment if it does not reference a value.
79557             return resolver.isValueAliasDeclaration(node)
79558                 ? ts.visitEachChild(node, visitor, context)
79559                 : undefined;
79560         }
79561         /**
79562          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79563          * to a value.
79564          *
79565          * @param node The export declaration node.
79566          */
79567         function visitExportDeclaration(node) {
79568             if (node.isTypeOnly) {
79569                 return undefined;
79570             }
79571             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79572                 // never elide `export <whatever> from <whereever>` declarations -
79573                 // they should be kept for sideffects/untyped exports, even when the
79574                 // type checker doesn't know about any exports
79575                 return node;
79576             }
79577             if (!resolver.isValueAliasDeclaration(node)) {
79578                 // Elide the export declaration if it does not export a value.
79579                 return undefined;
79580             }
79581             // Elide the export declaration if all of its named exports are elided.
79582             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79583             return exportClause
79584                 ? ts.updateExportDeclaration(node, 
79585                 /*decorators*/ undefined, 
79586                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79587                 : undefined;
79588         }
79589         /**
79590          * Visits named exports, eliding it if it does not contain an export specifier that
79591          * resolves to a value.
79592          *
79593          * @param node The named exports node.
79594          */
79595         function visitNamedExports(node) {
79596             // Elide the named exports if all of its export specifiers were elided.
79597             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79598             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79599         }
79600         function visitNamespaceExports(node) {
79601             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79602         }
79603         function visitNamedExportBindings(node) {
79604             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79605         }
79606         /**
79607          * Visits an export specifier, eliding it if it does not resolve to a value.
79608          *
79609          * @param node The export specifier node.
79610          */
79611         function visitExportSpecifier(node) {
79612             // Elide an export specifier if it does not reference a value.
79613             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79614         }
79615         /**
79616          * Determines whether to emit an import equals declaration.
79617          *
79618          * @param node The import equals declaration node.
79619          */
79620         function shouldEmitImportEqualsDeclaration(node) {
79621             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79622             // - current file is not external module
79623             // - import declaration is top level and target is value imported by entity name
79624             return resolver.isReferencedAliasDeclaration(node)
79625                 || (!ts.isExternalModule(currentSourceFile)
79626                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79627         }
79628         /**
79629          * Visits an import equals declaration.
79630          *
79631          * @param node The import equals declaration node.
79632          */
79633         function visitImportEqualsDeclaration(node) {
79634             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79635                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79636                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79637                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79638                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79639                     /*decorators*/ undefined, 
79640                     /*modifiers*/ undefined, 
79641                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79642                 }
79643                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79644             }
79645             if (!shouldEmitImportEqualsDeclaration(node)) {
79646                 return undefined;
79647             }
79648             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79649             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79650             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79651                 //  export var ${name} = ${moduleReference};
79652                 //  var ${name} = ${moduleReference};
79653                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79654                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79655                     /*type*/ undefined, moduleReference), node)
79656                 ])), node), node);
79657             }
79658             else {
79659                 // exports.${name} = ${moduleReference};
79660                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79661             }
79662         }
79663         /**
79664          * Gets a value indicating whether the node is exported from a namespace.
79665          *
79666          * @param node The node to test.
79667          */
79668         function isExportOfNamespace(node) {
79669             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79670         }
79671         /**
79672          * Gets a value indicating whether the node is exported from an external module.
79673          *
79674          * @param node The node to test.
79675          */
79676         function isExternalModuleExport(node) {
79677             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79678         }
79679         /**
79680          * Gets a value indicating whether the node is a named export from an external module.
79681          *
79682          * @param node The node to test.
79683          */
79684         function isNamedExternalModuleExport(node) {
79685             return isExternalModuleExport(node)
79686                 && !ts.hasModifier(node, 512 /* Default */);
79687         }
79688         /**
79689          * Gets a value indicating whether the node is the default export of an external module.
79690          *
79691          * @param node The node to test.
79692          */
79693         function isDefaultExternalModuleExport(node) {
79694             return isExternalModuleExport(node)
79695                 && ts.hasModifier(node, 512 /* Default */);
79696         }
79697         /**
79698          * Creates a statement for the provided expression. This is used in calls to `map`.
79699          */
79700         function expressionToStatement(expression) {
79701             return ts.createExpressionStatement(expression);
79702         }
79703         function addExportMemberAssignment(statements, node) {
79704             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79705             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79706             var statement = ts.createExpressionStatement(expression);
79707             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79708             statements.push(statement);
79709         }
79710         function createNamespaceExport(exportName, exportValue, location) {
79711             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79712         }
79713         function createNamespaceExportExpression(exportName, exportValue, location) {
79714             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79715         }
79716         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79717             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79718         }
79719         /**
79720          * Gets the declaration name used inside of a namespace or enum.
79721          */
79722         function getNamespaceParameterName(node) {
79723             var name = ts.getGeneratedNameForNode(node);
79724             ts.setSourceMapRange(name, node.name);
79725             return name;
79726         }
79727         /**
79728          * Gets the expression used to refer to a namespace or enum within the body
79729          * of its declaration.
79730          */
79731         function getNamespaceContainerName(node) {
79732             return ts.getGeneratedNameForNode(node);
79733         }
79734         /**
79735          * Gets a local alias for a class declaration if it is a decorated class with an internal
79736          * reference to the static side of the class. This is necessary to avoid issues with
79737          * double-binding semantics for the class name.
79738          */
79739         function getClassAliasIfNeeded(node) {
79740             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79741                 enableSubstitutionForClassAliases();
79742                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79743                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79744                 hoistVariableDeclaration(classAlias);
79745                 return classAlias;
79746             }
79747         }
79748         function getClassPrototype(node) {
79749             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79750         }
79751         function getClassMemberPrefix(node, member) {
79752             return ts.hasModifier(member, 32 /* Static */)
79753                 ? ts.getDeclarationName(node)
79754                 : getClassPrototype(node);
79755         }
79756         function enableSubstitutionForNonQualifiedEnumMembers() {
79757             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79758                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79759                 context.enableSubstitution(75 /* Identifier */);
79760             }
79761         }
79762         function enableSubstitutionForClassAliases() {
79763             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79764                 enabledSubstitutions |= 1 /* ClassAliases */;
79765                 // We need to enable substitutions for identifiers. This allows us to
79766                 // substitute class names inside of a class declaration.
79767                 context.enableSubstitution(75 /* Identifier */);
79768                 // Keep track of class aliases.
79769                 classAliases = [];
79770             }
79771         }
79772         function enableSubstitutionForNamespaceExports() {
79773             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79774                 enabledSubstitutions |= 2 /* NamespaceExports */;
79775                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79776                 // substitute the names of exported members of a namespace.
79777                 context.enableSubstitution(75 /* Identifier */);
79778                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79779                 // We need to be notified when entering and exiting namespaces.
79780                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79781             }
79782         }
79783         function isTransformedModuleDeclaration(node) {
79784             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79785         }
79786         function isTransformedEnumDeclaration(node) {
79787             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79788         }
79789         /**
79790          * Hook for node emit.
79791          *
79792          * @param hint A hint as to the intended usage of the node.
79793          * @param node The node to emit.
79794          * @param emit A callback used to emit the node in the printer.
79795          */
79796         function onEmitNode(hint, node, emitCallback) {
79797             var savedApplicableSubstitutions = applicableSubstitutions;
79798             var savedCurrentSourceFile = currentSourceFile;
79799             if (ts.isSourceFile(node)) {
79800                 currentSourceFile = node;
79801             }
79802             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79803                 applicableSubstitutions |= 2 /* NamespaceExports */;
79804             }
79805             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79806                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79807             }
79808             previousOnEmitNode(hint, node, emitCallback);
79809             applicableSubstitutions = savedApplicableSubstitutions;
79810             currentSourceFile = savedCurrentSourceFile;
79811         }
79812         /**
79813          * Hooks node substitutions.
79814          *
79815          * @param hint A hint as to the intended usage of the node.
79816          * @param node The node to substitute.
79817          */
79818         function onSubstituteNode(hint, node) {
79819             node = previousOnSubstituteNode(hint, node);
79820             if (hint === 1 /* Expression */) {
79821                 return substituteExpression(node);
79822             }
79823             else if (ts.isShorthandPropertyAssignment(node)) {
79824                 return substituteShorthandPropertyAssignment(node);
79825             }
79826             return node;
79827         }
79828         function substituteShorthandPropertyAssignment(node) {
79829             if (enabledSubstitutions & 2 /* NamespaceExports */) {
79830                 var name = node.name;
79831                 var exportedName = trySubstituteNamespaceExportedName(name);
79832                 if (exportedName) {
79833                     // A shorthand property with an assignment initializer is probably part of a
79834                     // destructuring assignment
79835                     if (node.objectAssignmentInitializer) {
79836                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
79837                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79838                     }
79839                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
79840                 }
79841             }
79842             return node;
79843         }
79844         function substituteExpression(node) {
79845             switch (node.kind) {
79846                 case 75 /* Identifier */:
79847                     return substituteExpressionIdentifier(node);
79848                 case 194 /* PropertyAccessExpression */:
79849                     return substitutePropertyAccessExpression(node);
79850                 case 195 /* ElementAccessExpression */:
79851                     return substituteElementAccessExpression(node);
79852             }
79853             return node;
79854         }
79855         function substituteExpressionIdentifier(node) {
79856             return trySubstituteClassAlias(node)
79857                 || trySubstituteNamespaceExportedName(node)
79858                 || node;
79859         }
79860         function trySubstituteClassAlias(node) {
79861             if (enabledSubstitutions & 1 /* ClassAliases */) {
79862                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
79863                     // Due to the emit for class decorators, any reference to the class from inside of the class body
79864                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
79865                     // behavior of class names in ES6.
79866                     // Also, when emitting statics for class expressions, we must substitute a class alias for
79867                     // constructor references in static property initializers.
79868                     var declaration = resolver.getReferencedValueDeclaration(node);
79869                     if (declaration) {
79870                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
79871                         if (classAlias) {
79872                             var clone_1 = ts.getSynthesizedClone(classAlias);
79873                             ts.setSourceMapRange(clone_1, node);
79874                             ts.setCommentRange(clone_1, node);
79875                             return clone_1;
79876                         }
79877                     }
79878                 }
79879             }
79880             return undefined;
79881         }
79882         function trySubstituteNamespaceExportedName(node) {
79883             // If this is explicitly a local name, do not substitute.
79884             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79885                 // If we are nested within a namespace declaration, we may need to qualifiy
79886                 // an identifier that is exported from a merged namespace.
79887                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
79888                 if (container && container.kind !== 290 /* SourceFile */) {
79889                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
79890                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
79891                     if (substitute) {
79892                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
79893                         /*location*/ node);
79894                     }
79895                 }
79896             }
79897             return undefined;
79898         }
79899         function substitutePropertyAccessExpression(node) {
79900             return substituteConstantValue(node);
79901         }
79902         function substituteElementAccessExpression(node) {
79903             return substituteConstantValue(node);
79904         }
79905         function substituteConstantValue(node) {
79906             var constantValue = tryGetConstEnumValue(node);
79907             if (constantValue !== undefined) {
79908                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
79909                 ts.setConstantValue(node, constantValue);
79910                 var substitute = ts.createLiteral(constantValue);
79911                 if (!compilerOptions.removeComments) {
79912                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
79913                     var propertyName = ts.isPropertyAccessExpression(originalNode)
79914                         ? ts.declarationNameToString(originalNode.name)
79915                         : ts.getTextOfNode(originalNode.argumentExpression);
79916                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
79917                 }
79918                 return substitute;
79919             }
79920             return node;
79921         }
79922         function tryGetConstEnumValue(node) {
79923             if (compilerOptions.isolatedModules) {
79924                 return undefined;
79925             }
79926             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
79927         }
79928     }
79929     ts.transformTypeScript = transformTypeScript;
79930     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
79931         var argumentsArray = [];
79932         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
79933         argumentsArray.push(target);
79934         if (memberName) {
79935             argumentsArray.push(memberName);
79936             if (descriptor) {
79937                 argumentsArray.push(descriptor);
79938             }
79939         }
79940         context.requestEmitHelper(ts.decorateHelper);
79941         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
79942         /*typeArguments*/ undefined, argumentsArray), location);
79943     }
79944     ts.decorateHelper = {
79945         name: "typescript:decorate",
79946         importName: "__decorate",
79947         scoped: false,
79948         priority: 2,
79949         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            };"
79950     };
79951     function createMetadataHelper(context, metadataKey, metadataValue) {
79952         context.requestEmitHelper(ts.metadataHelper);
79953         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
79954         /*typeArguments*/ undefined, [
79955             ts.createLiteral(metadataKey),
79956             metadataValue
79957         ]);
79958     }
79959     ts.metadataHelper = {
79960         name: "typescript:metadata",
79961         importName: "__metadata",
79962         scoped: false,
79963         priority: 3,
79964         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            };"
79965     };
79966     function createParamHelper(context, expression, parameterOffset, location) {
79967         context.requestEmitHelper(ts.paramHelper);
79968         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
79969         /*typeArguments*/ undefined, [
79970             ts.createLiteral(parameterOffset),
79971             expression
79972         ]), location);
79973     }
79974     ts.paramHelper = {
79975         name: "typescript:param",
79976         importName: "__param",
79977         scoped: false,
79978         priority: 4,
79979         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
79980     };
79981 })(ts || (ts = {}));
79982 /*@internal*/
79983 var ts;
79984 (function (ts) {
79985     var ClassPropertySubstitutionFlags;
79986     (function (ClassPropertySubstitutionFlags) {
79987         /**
79988          * Enables substitutions for class expressions with static fields
79989          * which have initializers that reference the class name.
79990          */
79991         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
79992     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
79993     var PrivateIdentifierPlacement;
79994     (function (PrivateIdentifierPlacement) {
79995         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
79996     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
79997     /**
79998      * Transforms ECMAScript Class Syntax.
79999      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80000      * For now, this transforms public field declarations using TypeScript class semantics,
80001      * where declarations are elided and initializers are transformed as assignments in the constructor.
80002      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80003      */
80004     function transformClassFields(context) {
80005         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80006         var resolver = context.getEmitResolver();
80007         var compilerOptions = context.getCompilerOptions();
80008         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80009         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80010         var previousOnSubstituteNode = context.onSubstituteNode;
80011         context.onSubstituteNode = onSubstituteNode;
80012         var enabledSubstitutions;
80013         var classAliases;
80014         /**
80015          * Tracks what computed name expressions originating from elided names must be inlined
80016          * at the next execution site, in document order
80017          */
80018         var pendingExpressions;
80019         /**
80020          * Tracks what computed name expression statements and static property initializers must be
80021          * emitted at the next execution site, in document order (for decorated classes).
80022          */
80023         var pendingStatements;
80024         var privateIdentifierEnvironmentStack = [];
80025         var currentPrivateIdentifierEnvironment;
80026         return ts.chainBundle(transformSourceFile);
80027         function transformSourceFile(node) {
80028             var options = context.getCompilerOptions();
80029             if (node.isDeclarationFile
80030                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80031                 return node;
80032             }
80033             var visited = ts.visitEachChild(node, visitor, context);
80034             ts.addEmitHelpers(visited, context.readEmitHelpers());
80035             return visited;
80036         }
80037         function visitor(node) {
80038             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80039                 return node;
80040             switch (node.kind) {
80041                 case 214 /* ClassExpression */:
80042                 case 245 /* ClassDeclaration */:
80043                     return visitClassLike(node);
80044                 case 159 /* PropertyDeclaration */:
80045                     return visitPropertyDeclaration(node);
80046                 case 225 /* VariableStatement */:
80047                     return visitVariableStatement(node);
80048                 case 154 /* ComputedPropertyName */:
80049                     return visitComputedPropertyName(node);
80050                 case 194 /* PropertyAccessExpression */:
80051                     return visitPropertyAccessExpression(node);
80052                 case 207 /* PrefixUnaryExpression */:
80053                     return visitPrefixUnaryExpression(node);
80054                 case 208 /* PostfixUnaryExpression */:
80055                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80056                 case 196 /* CallExpression */:
80057                     return visitCallExpression(node);
80058                 case 209 /* BinaryExpression */:
80059                     return visitBinaryExpression(node);
80060                 case 76 /* PrivateIdentifier */:
80061                     return visitPrivateIdentifier(node);
80062                 case 226 /* ExpressionStatement */:
80063                     return visitExpressionStatement(node);
80064                 case 230 /* ForStatement */:
80065                     return visitForStatement(node);
80066                 case 198 /* TaggedTemplateExpression */:
80067                     return visitTaggedTemplateExpression(node);
80068             }
80069             return ts.visitEachChild(node, visitor, context);
80070         }
80071         function visitorDestructuringTarget(node) {
80072             switch (node.kind) {
80073                 case 193 /* ObjectLiteralExpression */:
80074                 case 192 /* ArrayLiteralExpression */:
80075                     return visitAssignmentPattern(node);
80076                 default:
80077                     return visitor(node);
80078             }
80079         }
80080         /**
80081          * If we visit a private name, this means it is an undeclared private name.
80082          * Replace it with an empty identifier to indicate a problem with the code.
80083          */
80084         function visitPrivateIdentifier(node) {
80085             if (!shouldTransformPrivateFields) {
80086                 return node;
80087             }
80088             return ts.setOriginalNode(ts.createIdentifier(""), node);
80089         }
80090         /**
80091          * Visits the members of a class that has fields.
80092          *
80093          * @param node The node to visit.
80094          */
80095         function classElementVisitor(node) {
80096             switch (node.kind) {
80097                 case 162 /* Constructor */:
80098                     // Constructors for classes using class fields are transformed in
80099                     // `visitClassDeclaration` or `visitClassExpression`.
80100                     return undefined;
80101                 case 163 /* GetAccessor */:
80102                 case 164 /* SetAccessor */:
80103                 case 161 /* MethodDeclaration */:
80104                     // Visit the name of the member (if it's a computed property name).
80105                     return ts.visitEachChild(node, classElementVisitor, context);
80106                 case 159 /* PropertyDeclaration */:
80107                     return visitPropertyDeclaration(node);
80108                 case 154 /* ComputedPropertyName */:
80109                     return visitComputedPropertyName(node);
80110                 case 222 /* SemicolonClassElement */:
80111                     return node;
80112                 default:
80113                     return visitor(node);
80114             }
80115         }
80116         function visitVariableStatement(node) {
80117             var savedPendingStatements = pendingStatements;
80118             pendingStatements = [];
80119             var visitedNode = ts.visitEachChild(node, visitor, context);
80120             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80121                 visitedNode;
80122             pendingStatements = savedPendingStatements;
80123             return statement;
80124         }
80125         function visitComputedPropertyName(name) {
80126             var node = ts.visitEachChild(name, visitor, context);
80127             if (ts.some(pendingExpressions)) {
80128                 var expressions = pendingExpressions;
80129                 expressions.push(name.expression);
80130                 pendingExpressions = [];
80131                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80132             }
80133             return node;
80134         }
80135         function visitPropertyDeclaration(node) {
80136             ts.Debug.assert(!ts.some(node.decorators));
80137             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80138                 // Initializer is elided as the field is initialized in transformConstructor.
80139                 return ts.updateProperty(node, 
80140                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80141                 /*questionOrExclamationToken*/ undefined, 
80142                 /*type*/ undefined, 
80143                 /*initializer*/ undefined);
80144             }
80145             // Create a temporary variable to store a computed property name (if necessary).
80146             // If it's not inlineable, then we emit an expression after the class which assigns
80147             // the property name to the temporary variable.
80148             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80149             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80150                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80151             }
80152             return undefined;
80153         }
80154         function createPrivateIdentifierAccess(info, receiver) {
80155             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80156             switch (info.placement) {
80157                 case 0 /* InstanceField */:
80158                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80159                 default: return ts.Debug.fail("Unexpected private identifier placement");
80160             }
80161         }
80162         function visitPropertyAccessExpression(node) {
80163             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80164                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80165                 if (privateIdentifierInfo) {
80166                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80167                 }
80168             }
80169             return ts.visitEachChild(node, visitor, context);
80170         }
80171         function visitPrefixUnaryExpression(node) {
80172             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80173                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80174                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80175                     40 /* MinusToken */ : undefined;
80176                 var info = void 0;
80177                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80178                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80179                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80180                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80181                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80182                 }
80183             }
80184             return ts.visitEachChild(node, visitor, context);
80185         }
80186         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80187             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80188                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80189                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80190                     40 /* MinusToken */ : undefined;
80191                 var info = void 0;
80192                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80193                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80194                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80195                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80196                     // Create a temporary variable to store the value returned by the expression.
80197                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80198                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80199                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80200                         returnValue
80201                     ])), node);
80202                 }
80203             }
80204             return ts.visitEachChild(node, visitor, context);
80205         }
80206         function visitForStatement(node) {
80207             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80208                 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));
80209             }
80210             return ts.visitEachChild(node, visitor, context);
80211         }
80212         function visitExpressionStatement(node) {
80213             if (ts.isPostfixUnaryExpression(node.expression)) {
80214                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80215             }
80216             return ts.visitEachChild(node, visitor, context);
80217         }
80218         function createCopiableReceiverExpr(receiver) {
80219             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80220             if (ts.isSimpleInlineableExpression(receiver)) {
80221                 return { readExpression: clone, initializeExpression: undefined };
80222             }
80223             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80224             var initializeExpression = ts.createAssignment(readExpression, clone);
80225             return { readExpression: readExpression, initializeExpression: initializeExpression };
80226         }
80227         function visitCallExpression(node) {
80228             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80229                 // Transform call expressions of private names to properly bind the `this` parameter.
80230                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80231                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80232                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80233             }
80234             return ts.visitEachChild(node, visitor, context);
80235         }
80236         function visitTaggedTemplateExpression(node) {
80237             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80238                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80239                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80240                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80241                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80242             }
80243             return ts.visitEachChild(node, visitor, context);
80244         }
80245         function visitBinaryExpression(node) {
80246             if (shouldTransformPrivateFields) {
80247                 if (ts.isDestructuringAssignment(node)) {
80248                     var savedPendingExpressions = pendingExpressions;
80249                     pendingExpressions = undefined;
80250                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80251                     var expr = ts.some(pendingExpressions) ?
80252                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80253                         node;
80254                     pendingExpressions = savedPendingExpressions;
80255                     return expr;
80256                 }
80257                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80258                     var info = accessPrivateIdentifier(node.left.name);
80259                     if (info) {
80260                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80261                     }
80262                 }
80263             }
80264             return ts.visitEachChild(node, visitor, context);
80265         }
80266         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80267             switch (info.placement) {
80268                 case 0 /* InstanceField */: {
80269                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80270                 }
80271                 default: return ts.Debug.fail("Unexpected private identifier placement");
80272             }
80273         }
80274         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80275             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80276             right = ts.visitNode(right, visitor, ts.isExpression);
80277             if (ts.isCompoundAssignment(operator)) {
80278                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80279                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80280             }
80281             else {
80282                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80283             }
80284         }
80285         /**
80286          * Set up the environment for a class.
80287          */
80288         function visitClassLike(node) {
80289             var savedPendingExpressions = pendingExpressions;
80290             pendingExpressions = undefined;
80291             if (shouldTransformPrivateFields) {
80292                 startPrivateIdentifierEnvironment();
80293             }
80294             var result = ts.isClassDeclaration(node) ?
80295                 visitClassDeclaration(node) :
80296                 visitClassExpression(node);
80297             if (shouldTransformPrivateFields) {
80298                 endPrivateIdentifierEnvironment();
80299             }
80300             pendingExpressions = savedPendingExpressions;
80301             return result;
80302         }
80303         function doesClassElementNeedTransform(node) {
80304             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80305         }
80306         function visitClassDeclaration(node) {
80307             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80308                 return ts.visitEachChild(node, visitor, context);
80309             }
80310             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80311             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80312             var statements = [
80313                 ts.updateClassDeclaration(node, 
80314                 /*decorators*/ undefined, node.modifiers, node.name, 
80315                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80316             ];
80317             // Write any pending expressions from elided or moved computed property names
80318             if (ts.some(pendingExpressions)) {
80319                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80320             }
80321             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80322             // it is safe to emit static property assignment after classDeclaration
80323             // From ES6 specification:
80324             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80325             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80326             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80327             if (ts.some(staticProperties)) {
80328                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80329             }
80330             return statements;
80331         }
80332         function visitClassExpression(node) {
80333             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80334                 return ts.visitEachChild(node, visitor, context);
80335             }
80336             // If this class expression is a transformation of a decorated class declaration,
80337             // then we want to output the pendingExpressions as statements, not as inlined
80338             // expressions with the class statement.
80339             //
80340             // In this case, we use pendingStatements to produce the same output as the
80341             // class declaration transformation. The VariableStatement visitor will insert
80342             // these statements after the class expression variable statement.
80343             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80344             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80345             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80346             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80347             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80348             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80349             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80350                 if (isDecoratedClassDeclaration) {
80351                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80352                     // Write any pending expressions from elided or moved computed property names
80353                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80354                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80355                     }
80356                     if (pendingStatements && ts.some(staticProperties)) {
80357                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80358                     }
80359                     return classExpression;
80360                 }
80361                 else {
80362                     var expressions = [];
80363                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80364                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80365                     if (isClassWithConstructorReference) {
80366                         // record an alias as the class name is not in scope for statics.
80367                         enableSubstitutionForClassAliases();
80368                         var alias = ts.getSynthesizedClone(temp);
80369                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80370                         classAliases[ts.getOriginalNodeId(node)] = alias;
80371                     }
80372                     // To preserve the behavior of the old emitter, we explicitly indent
80373                     // the body of a class with static initializers.
80374                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80375                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80376                     // Add any pending expressions leftover from elided or relocated computed property names
80377                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80378                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80379                     expressions.push(ts.startOnNewLine(temp));
80380                     return ts.inlineExpressions(expressions);
80381                 }
80382             }
80383             return classExpression;
80384         }
80385         function transformClassMembers(node, isDerivedClass) {
80386             if (shouldTransformPrivateFields) {
80387                 // Declare private names.
80388                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80389                     var member = _a[_i];
80390                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80391                         addPrivateIdentifierToEnvironment(member.name);
80392                     }
80393                 }
80394             }
80395             var members = [];
80396             var constructor = transformConstructor(node, isDerivedClass);
80397             if (constructor) {
80398                 members.push(constructor);
80399             }
80400             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80401             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80402         }
80403         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80404             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80405                 return false;
80406             }
80407             if (context.getCompilerOptions().useDefineForClassFields) {
80408                 // If we are using define semantics and targeting ESNext or higher,
80409                 // then we don't need to transform any class properties.
80410                 return languageVersion < 99 /* ESNext */;
80411             }
80412             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80413         }
80414         function transformConstructor(node, isDerivedClass) {
80415             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80416             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80417             if (!ts.some(properties)) {
80418                 return constructor;
80419             }
80420             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80421             var body = transformConstructorBody(node, constructor, isDerivedClass);
80422             if (!body) {
80423                 return undefined;
80424             }
80425             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80426             /*decorators*/ undefined, 
80427             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80428         }
80429         function transformConstructorBody(node, constructor, isDerivedClass) {
80430             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80431             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80432             if (!useDefineForClassFields) {
80433                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80434             }
80435             // Only generate synthetic constructor when there are property initializers to move.
80436             if (!constructor && !ts.some(properties)) {
80437                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80438             }
80439             resumeLexicalEnvironment();
80440             var indexOfFirstStatement = 0;
80441             var statements = [];
80442             if (!constructor && isDerivedClass) {
80443                 // Add a synthetic `super` call:
80444                 //
80445                 //  super(...arguments);
80446                 //
80447                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80448                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80449             }
80450             if (constructor) {
80451                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80452             }
80453             // Add the property initializers. Transforms this:
80454             //
80455             //  public x = 1;
80456             //
80457             // Into this:
80458             //
80459             //  constructor() {
80460             //      this.x = 1;
80461             //  }
80462             //
80463             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80464                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80465                 if (afterParameterProperties === -1) {
80466                     afterParameterProperties = constructor.body.statements.length;
80467                 }
80468                 if (afterParameterProperties > indexOfFirstStatement) {
80469                     if (!useDefineForClassFields) {
80470                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80471                     }
80472                     indexOfFirstStatement = afterParameterProperties;
80473                 }
80474             }
80475             addPropertyStatements(statements, properties, ts.createThis());
80476             // Add existing statements, skipping the initial super call.
80477             if (constructor) {
80478                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80479             }
80480             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80481             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80482             /*location*/ constructor ? constructor.body.statements : node.members), 
80483             /*multiLine*/ true), 
80484             /*location*/ constructor ? constructor.body : undefined);
80485         }
80486         /**
80487          * Generates assignment statements for property initializers.
80488          *
80489          * @param properties An array of property declarations to transform.
80490          * @param receiver The receiver on which each property should be assigned.
80491          */
80492         function addPropertyStatements(statements, properties, receiver) {
80493             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80494                 var property = properties_8[_i];
80495                 var expression = transformProperty(property, receiver);
80496                 if (!expression) {
80497                     continue;
80498                 }
80499                 var statement = ts.createExpressionStatement(expression);
80500                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80501                 ts.setCommentRange(statement, property);
80502                 ts.setOriginalNode(statement, property);
80503                 statements.push(statement);
80504             }
80505         }
80506         /**
80507          * Generates assignment expressions for property initializers.
80508          *
80509          * @param properties An array of property declarations to transform.
80510          * @param receiver The receiver on which each property should be assigned.
80511          */
80512         function generateInitializedPropertyExpressions(properties, receiver) {
80513             var expressions = [];
80514             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80515                 var property = properties_9[_i];
80516                 var expression = transformProperty(property, receiver);
80517                 if (!expression) {
80518                     continue;
80519                 }
80520                 ts.startOnNewLine(expression);
80521                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80522                 ts.setCommentRange(expression, property);
80523                 ts.setOriginalNode(expression, property);
80524                 expressions.push(expression);
80525             }
80526             return expressions;
80527         }
80528         /**
80529          * Transforms a property initializer into an assignment statement.
80530          *
80531          * @param property The property declaration.
80532          * @param receiver The object receiving the property assignment.
80533          */
80534         function transformProperty(property, receiver) {
80535             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80536             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80537             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80538                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80539                 : property.name;
80540             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80541                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80542                 if (privateIdentifierInfo) {
80543                     switch (privateIdentifierInfo.placement) {
80544                         case 0 /* InstanceField */: {
80545                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80546                         }
80547                     }
80548                 }
80549                 else {
80550                     ts.Debug.fail("Undeclared private name for property declaration.");
80551                 }
80552             }
80553             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80554                 return undefined;
80555             }
80556             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80557                 return undefined;
80558             }
80559             var propertyOriginalNode = ts.getOriginalNode(property);
80560             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80561                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80562                     : ts.createVoidZero();
80563             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80564                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80565                 return ts.createAssignment(memberAccess, initializer);
80566             }
80567             else {
80568                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80569                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80570                         : propertyName;
80571                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80572                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80573             }
80574         }
80575         function enableSubstitutionForClassAliases() {
80576             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80577                 enabledSubstitutions |= 1 /* ClassAliases */;
80578                 // We need to enable substitutions for identifiers. This allows us to
80579                 // substitute class names inside of a class declaration.
80580                 context.enableSubstitution(75 /* Identifier */);
80581                 // Keep track of class aliases.
80582                 classAliases = [];
80583             }
80584         }
80585         /**
80586          * Hooks node substitutions.
80587          *
80588          * @param hint The context for the emitter.
80589          * @param node The node to substitute.
80590          */
80591         function onSubstituteNode(hint, node) {
80592             node = previousOnSubstituteNode(hint, node);
80593             if (hint === 1 /* Expression */) {
80594                 return substituteExpression(node);
80595             }
80596             return node;
80597         }
80598         function substituteExpression(node) {
80599             switch (node.kind) {
80600                 case 75 /* Identifier */:
80601                     return substituteExpressionIdentifier(node);
80602             }
80603             return node;
80604         }
80605         function substituteExpressionIdentifier(node) {
80606             return trySubstituteClassAlias(node) || node;
80607         }
80608         function trySubstituteClassAlias(node) {
80609             if (enabledSubstitutions & 1 /* ClassAliases */) {
80610                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80611                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80612                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80613                     // behavior of class names in ES6.
80614                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80615                     // constructor references in static property initializers.
80616                     var declaration = resolver.getReferencedValueDeclaration(node);
80617                     if (declaration) {
80618                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80619                         if (classAlias) {
80620                             var clone_2 = ts.getSynthesizedClone(classAlias);
80621                             ts.setSourceMapRange(clone_2, node);
80622                             ts.setCommentRange(clone_2, node);
80623                             return clone_2;
80624                         }
80625                     }
80626                 }
80627             }
80628             return undefined;
80629         }
80630         /**
80631          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80632          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80633          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80634          */
80635         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80636             if (ts.isComputedPropertyName(name)) {
80637                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80638                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80639                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80640                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80641                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80642                     var generatedName = ts.getGeneratedNameForNode(name);
80643                     hoistVariableDeclaration(generatedName);
80644                     return ts.createAssignment(generatedName, expression);
80645                 }
80646                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80647             }
80648         }
80649         function startPrivateIdentifierEnvironment() {
80650             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80651             currentPrivateIdentifierEnvironment = undefined;
80652         }
80653         function endPrivateIdentifierEnvironment() {
80654             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80655         }
80656         function addPrivateIdentifierToEnvironment(name) {
80657             var text = ts.getTextOfPropertyName(name);
80658             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80659             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80660             hoistVariableDeclaration(weakMapName);
80661             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80662                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80663             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80664             /*typeArguments*/ undefined, [])));
80665         }
80666         function accessPrivateIdentifier(name) {
80667             if (currentPrivateIdentifierEnvironment) {
80668                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80669                 if (info) {
80670                     return info;
80671                 }
80672             }
80673             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80674                 var env = privateIdentifierEnvironmentStack[i];
80675                 if (!env) {
80676                     continue;
80677                 }
80678                 var info = env.get(name.escapedText);
80679                 if (info) {
80680                     return info;
80681                 }
80682             }
80683             return undefined;
80684         }
80685         function wrapPrivateIdentifierForDestructuringTarget(node) {
80686             var parameter = ts.getGeneratedNameForNode(node);
80687             var info = accessPrivateIdentifier(node.name);
80688             if (!info) {
80689                 return ts.visitEachChild(node, visitor, context);
80690             }
80691             var receiver = node.expression;
80692             // We cannot copy `this` or `super` into the function because they will be bound
80693             // differently inside the function.
80694             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80695                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80696                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80697                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80698             }
80699             return ts.createPropertyAccess(
80700             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80701             ts.createParen(ts.createObjectLiteral([
80702                 ts.createSetAccessor(
80703                 /*decorators*/ undefined, 
80704                 /*modifiers*/ undefined, "value", [ts.createParameter(
80705                     /*decorators*/ undefined, 
80706                     /*modifiers*/ undefined, 
80707                     /*dotDotDotToken*/ undefined, parameter, 
80708                     /*questionToken*/ undefined, 
80709                     /*type*/ undefined, 
80710                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80711             ])), "value");
80712         }
80713         function visitArrayAssignmentTarget(node) {
80714             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80715             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80716                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80717                 if (ts.isAssignmentExpression(node)) {
80718                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80719                 }
80720                 else if (ts.isSpreadElement(node)) {
80721                     return ts.updateSpread(node, wrapped);
80722                 }
80723                 else {
80724                     return wrapped;
80725                 }
80726             }
80727             return ts.visitNode(node, visitorDestructuringTarget);
80728         }
80729         function visitObjectAssignmentTarget(node) {
80730             if (ts.isPropertyAssignment(node)) {
80731                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80732                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80733                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80734                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80735                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80736                 }
80737                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80738             }
80739             return ts.visitNode(node, visitor);
80740         }
80741         function visitAssignmentPattern(node) {
80742             if (ts.isArrayLiteralExpression(node)) {
80743                 // Transforms private names in destructuring assignment array bindings.
80744                 //
80745                 // Source:
80746                 // ([ this.#myProp ] = [ "hello" ]);
80747                 //
80748                 // Transformation:
80749                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80750                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80751             }
80752             else {
80753                 // Transforms private names in destructuring assignment object bindings.
80754                 //
80755                 // Source:
80756                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80757                 //
80758                 // Transformation:
80759                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80760                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80761             }
80762         }
80763     }
80764     ts.transformClassFields = transformClassFields;
80765     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80766         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80767         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80768     }
80769     ts.classPrivateFieldGetHelper = {
80770         name: "typescript:classPrivateFieldGet",
80771         scoped: false,
80772         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            };"
80773     };
80774     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80775         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80776         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80777     }
80778     ts.classPrivateFieldSetHelper = {
80779         name: "typescript:classPrivateFieldSet",
80780         scoped: false,
80781         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            };"
80782     };
80783     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80784         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80785         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80786     }
80787 })(ts || (ts = {}));
80788 /*@internal*/
80789 var ts;
80790 (function (ts) {
80791     var ES2017SubstitutionFlags;
80792     (function (ES2017SubstitutionFlags) {
80793         /** Enables substitutions for async methods with `super` calls. */
80794         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80795     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80796     var ContextFlags;
80797     (function (ContextFlags) {
80798         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80799         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80800     })(ContextFlags || (ContextFlags = {}));
80801     function transformES2017(context) {
80802         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80803         var resolver = context.getEmitResolver();
80804         var compilerOptions = context.getCompilerOptions();
80805         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80806         /**
80807          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80808          * They are persisted between each SourceFile transformation and should not be reset.
80809          */
80810         var enabledSubstitutions;
80811         /**
80812          * This keeps track of containers where `super` is valid, for use with
80813          * just-in-time substitution for `super` expressions inside of async methods.
80814          */
80815         var enclosingSuperContainerFlags = 0;
80816         var enclosingFunctionParameterNames;
80817         /**
80818          * Keeps track of property names accessed on super (`super.x`) within async functions.
80819          */
80820         var capturedSuperProperties;
80821         /** Whether the async function contains an element access on super (`super[x]`). */
80822         var hasSuperElementAccess;
80823         /** A set of node IDs for generated super accessors (variable statements). */
80824         var substitutedSuperAccessors = [];
80825         var contextFlags = 0;
80826         // Save the previous transformation hooks.
80827         var previousOnEmitNode = context.onEmitNode;
80828         var previousOnSubstituteNode = context.onSubstituteNode;
80829         // Set new transformation hooks.
80830         context.onEmitNode = onEmitNode;
80831         context.onSubstituteNode = onSubstituteNode;
80832         return ts.chainBundle(transformSourceFile);
80833         function transformSourceFile(node) {
80834             if (node.isDeclarationFile) {
80835                 return node;
80836             }
80837             setContextFlag(1 /* NonTopLevel */, false);
80838             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
80839             var visited = ts.visitEachChild(node, visitor, context);
80840             ts.addEmitHelpers(visited, context.readEmitHelpers());
80841             return visited;
80842         }
80843         function setContextFlag(flag, val) {
80844             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
80845         }
80846         function inContext(flags) {
80847             return (contextFlags & flags) !== 0;
80848         }
80849         function inTopLevelContext() {
80850             return !inContext(1 /* NonTopLevel */);
80851         }
80852         function inHasLexicalThisContext() {
80853             return inContext(2 /* HasLexicalThis */);
80854         }
80855         function doWithContext(flags, cb, value) {
80856             var contextFlagsToSet = flags & ~contextFlags;
80857             if (contextFlagsToSet) {
80858                 setContextFlag(contextFlagsToSet, /*val*/ true);
80859                 var result = cb(value);
80860                 setContextFlag(contextFlagsToSet, /*val*/ false);
80861                 return result;
80862             }
80863             return cb(value);
80864         }
80865         function visitDefault(node) {
80866             return ts.visitEachChild(node, visitor, context);
80867         }
80868         function visitor(node) {
80869             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
80870                 return node;
80871             }
80872             switch (node.kind) {
80873                 case 126 /* AsyncKeyword */:
80874                     // ES2017 async modifier should be elided for targets < ES2017
80875                     return undefined;
80876                 case 206 /* AwaitExpression */:
80877                     return visitAwaitExpression(node);
80878                 case 161 /* MethodDeclaration */:
80879                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
80880                 case 244 /* FunctionDeclaration */:
80881                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
80882                 case 201 /* FunctionExpression */:
80883                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
80884                 case 202 /* ArrowFunction */:
80885                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
80886                 case 194 /* PropertyAccessExpression */:
80887                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
80888                         capturedSuperProperties.set(node.name.escapedText, true);
80889                     }
80890                     return ts.visitEachChild(node, visitor, context);
80891                 case 195 /* ElementAccessExpression */:
80892                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
80893                         hasSuperElementAccess = true;
80894                     }
80895                     return ts.visitEachChild(node, visitor, context);
80896                 case 163 /* GetAccessor */:
80897                 case 164 /* SetAccessor */:
80898                 case 162 /* Constructor */:
80899                 case 245 /* ClassDeclaration */:
80900                 case 214 /* ClassExpression */:
80901                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
80902                 default:
80903                     return ts.visitEachChild(node, visitor, context);
80904             }
80905         }
80906         function asyncBodyVisitor(node) {
80907             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
80908                 switch (node.kind) {
80909                     case 225 /* VariableStatement */:
80910                         return visitVariableStatementInAsyncBody(node);
80911                     case 230 /* ForStatement */:
80912                         return visitForStatementInAsyncBody(node);
80913                     case 231 /* ForInStatement */:
80914                         return visitForInStatementInAsyncBody(node);
80915                     case 232 /* ForOfStatement */:
80916                         return visitForOfStatementInAsyncBody(node);
80917                     case 280 /* CatchClause */:
80918                         return visitCatchClauseInAsyncBody(node);
80919                     case 223 /* Block */:
80920                     case 237 /* SwitchStatement */:
80921                     case 251 /* CaseBlock */:
80922                     case 277 /* CaseClause */:
80923                     case 278 /* DefaultClause */:
80924                     case 240 /* TryStatement */:
80925                     case 228 /* DoStatement */:
80926                     case 229 /* WhileStatement */:
80927                     case 227 /* IfStatement */:
80928                     case 236 /* WithStatement */:
80929                     case 238 /* LabeledStatement */:
80930                         return ts.visitEachChild(node, asyncBodyVisitor, context);
80931                     default:
80932                         return ts.Debug.assertNever(node, "Unhandled node.");
80933                 }
80934             }
80935             return visitor(node);
80936         }
80937         function visitCatchClauseInAsyncBody(node) {
80938             var catchClauseNames = ts.createUnderscoreEscapedMap();
80939             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
80940             // names declared in a catch variable are block scoped
80941             var catchClauseUnshadowedNames;
80942             catchClauseNames.forEach(function (_, escapedName) {
80943                 if (enclosingFunctionParameterNames.has(escapedName)) {
80944                     if (!catchClauseUnshadowedNames) {
80945                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
80946                     }
80947                     catchClauseUnshadowedNames.delete(escapedName);
80948                 }
80949             });
80950             if (catchClauseUnshadowedNames) {
80951                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
80952                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
80953                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
80954                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
80955                 return result;
80956             }
80957             else {
80958                 return ts.visitEachChild(node, asyncBodyVisitor, context);
80959             }
80960         }
80961         function visitVariableStatementInAsyncBody(node) {
80962             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
80963                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
80964                 return expression ? ts.createExpressionStatement(expression) : undefined;
80965             }
80966             return ts.visitEachChild(node, visitor, context);
80967         }
80968         function visitForInStatementInAsyncBody(node) {
80969             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
80970                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80971                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
80972         }
80973         function visitForOfStatementInAsyncBody(node) {
80974             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
80975                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80976                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
80977         }
80978         function visitForStatementInAsyncBody(node) {
80979             var initializer = node.initializer; // TODO: GH#18217
80980             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
80981                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
80982                 : 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));
80983         }
80984         /**
80985          * Visits an AwaitExpression node.
80986          *
80987          * This function will be called any time a ES2017 await expression is encountered.
80988          *
80989          * @param node The node to visit.
80990          */
80991         function visitAwaitExpression(node) {
80992             // do not downlevel a top-level await as it is module syntax...
80993             if (inTopLevelContext()) {
80994                 return ts.visitEachChild(node, visitor, context);
80995             }
80996             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
80997             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
80998         }
80999         /**
81000          * Visits a MethodDeclaration node.
81001          *
81002          * This function will be called when one of the following conditions are met:
81003          * - The node is marked as async
81004          *
81005          * @param node The node to visit.
81006          */
81007         function visitMethodDeclaration(node) {
81008             return ts.updateMethod(node, 
81009             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81010             /*questionToken*/ undefined, 
81011             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81012             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81013                 ? transformAsyncFunctionBody(node)
81014                 : ts.visitFunctionBody(node.body, visitor, context));
81015         }
81016         /**
81017          * Visits a FunctionDeclaration node.
81018          *
81019          * This function will be called when one of the following conditions are met:
81020          * - The node is marked async
81021          *
81022          * @param node The node to visit.
81023          */
81024         function visitFunctionDeclaration(node) {
81025             return ts.updateFunctionDeclaration(node, 
81026             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81027             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81028             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81029                 ? transformAsyncFunctionBody(node)
81030                 : ts.visitFunctionBody(node.body, visitor, context));
81031         }
81032         /**
81033          * Visits a FunctionExpression node.
81034          *
81035          * This function will be called when one of the following conditions are met:
81036          * - The node is marked async
81037          *
81038          * @param node The node to visit.
81039          */
81040         function visitFunctionExpression(node) {
81041             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81042             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81043             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81044                 ? transformAsyncFunctionBody(node)
81045                 : ts.visitFunctionBody(node.body, visitor, context));
81046         }
81047         /**
81048          * Visits an ArrowFunction.
81049          *
81050          * This function will be called when one of the following conditions are met:
81051          * - The node is marked async
81052          *
81053          * @param node The node to visit.
81054          */
81055         function visitArrowFunction(node) {
81056             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81057             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81058             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81059                 ? transformAsyncFunctionBody(node)
81060                 : ts.visitFunctionBody(node.body, visitor, context));
81061         }
81062         function recordDeclarationName(_a, names) {
81063             var name = _a.name;
81064             if (ts.isIdentifier(name)) {
81065                 names.set(name.escapedText, true);
81066             }
81067             else {
81068                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81069                     var element = _b[_i];
81070                     if (!ts.isOmittedExpression(element)) {
81071                         recordDeclarationName(element, names);
81072                     }
81073                 }
81074             }
81075         }
81076         function isVariableDeclarationListWithCollidingName(node) {
81077             return !!node
81078                 && ts.isVariableDeclarationList(node)
81079                 && !(node.flags & 3 /* BlockScoped */)
81080                 && node.declarations.some(collidesWithParameterName);
81081         }
81082         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81083             hoistVariableDeclarationList(node);
81084             var variables = ts.getInitializedVariables(node);
81085             if (variables.length === 0) {
81086                 if (hasReceiver) {
81087                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81088                 }
81089                 return undefined;
81090             }
81091             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81092         }
81093         function hoistVariableDeclarationList(node) {
81094             ts.forEach(node.declarations, hoistVariable);
81095         }
81096         function hoistVariable(_a) {
81097             var name = _a.name;
81098             if (ts.isIdentifier(name)) {
81099                 hoistVariableDeclaration(name);
81100             }
81101             else {
81102                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81103                     var element = _b[_i];
81104                     if (!ts.isOmittedExpression(element)) {
81105                         hoistVariable(element);
81106                     }
81107                 }
81108             }
81109         }
81110         function transformInitializedVariable(node) {
81111             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81112             return ts.visitNode(converted, visitor, ts.isExpression);
81113         }
81114         function collidesWithParameterName(_a) {
81115             var name = _a.name;
81116             if (ts.isIdentifier(name)) {
81117                 return enclosingFunctionParameterNames.has(name.escapedText);
81118             }
81119             else {
81120                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81121                     var element = _b[_i];
81122                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81123                         return true;
81124                     }
81125                 }
81126             }
81127             return false;
81128         }
81129         function transformAsyncFunctionBody(node) {
81130             resumeLexicalEnvironment();
81131             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81132             var nodeType = original.type;
81133             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81134             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81135             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81136             // An async function is emit as an outer function that calls an inner
81137             // generator function. To preserve lexical bindings, we pass the current
81138             // `this` and `arguments` objects to `__awaiter`. The generator function
81139             // passed to `__awaiter` is executed inside of the callback to the
81140             // promise constructor.
81141             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81142             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81143             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81144                 var parameter = _a[_i];
81145                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81146             }
81147             var savedCapturedSuperProperties = capturedSuperProperties;
81148             var savedHasSuperElementAccess = hasSuperElementAccess;
81149             if (!isArrowFunction) {
81150                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81151                 hasSuperElementAccess = false;
81152             }
81153             var result;
81154             if (!isArrowFunction) {
81155                 var statements = [];
81156                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81157                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81158                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81159                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81160                 // This step isn't needed if we eventually transform this to ES5.
81161                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81162                 if (emitSuperHelpers) {
81163                     enableSubstitutionForAsyncMethodsWithSuper();
81164                     if (ts.hasEntries(capturedSuperProperties)) {
81165                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81166                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81167                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81168                     }
81169                 }
81170                 var block = ts.createBlock(statements, /*multiLine*/ true);
81171                 ts.setTextRange(block, node.body);
81172                 if (emitSuperHelpers && hasSuperElementAccess) {
81173                     // Emit helpers for super element access expressions (`super[x]`).
81174                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81175                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81176                     }
81177                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81178                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81179                     }
81180                 }
81181                 result = block;
81182             }
81183             else {
81184                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81185                 var declarations = endLexicalEnvironment();
81186                 if (ts.some(declarations)) {
81187                     var block = ts.convertToFunctionBody(expression);
81188                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81189                 }
81190                 else {
81191                     result = expression;
81192                 }
81193             }
81194             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81195             if (!isArrowFunction) {
81196                 capturedSuperProperties = savedCapturedSuperProperties;
81197                 hasSuperElementAccess = savedHasSuperElementAccess;
81198             }
81199             return result;
81200         }
81201         function transformAsyncFunctionBodyWorker(body, start) {
81202             if (ts.isBlock(body)) {
81203                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81204             }
81205             else {
81206                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81207             }
81208         }
81209         function getPromiseConstructor(type) {
81210             var typeName = type && ts.getEntityNameFromTypeNode(type);
81211             if (typeName && ts.isEntityName(typeName)) {
81212                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81213                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81214                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81215                     return typeName;
81216                 }
81217             }
81218             return undefined;
81219         }
81220         function enableSubstitutionForAsyncMethodsWithSuper() {
81221             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81222                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81223                 // We need to enable substitutions for call, property access, and element access
81224                 // if we need to rewrite super calls.
81225                 context.enableSubstitution(196 /* CallExpression */);
81226                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81227                 context.enableSubstitution(195 /* ElementAccessExpression */);
81228                 // We need to be notified when entering and exiting declarations that bind super.
81229                 context.enableEmitNotification(245 /* ClassDeclaration */);
81230                 context.enableEmitNotification(161 /* MethodDeclaration */);
81231                 context.enableEmitNotification(163 /* GetAccessor */);
81232                 context.enableEmitNotification(164 /* SetAccessor */);
81233                 context.enableEmitNotification(162 /* Constructor */);
81234                 // We need to be notified when entering the generated accessor arrow functions.
81235                 context.enableEmitNotification(225 /* VariableStatement */);
81236             }
81237         }
81238         /**
81239          * Hook for node emit.
81240          *
81241          * @param hint A hint as to the intended usage of the node.
81242          * @param node The node to emit.
81243          * @param emit A callback used to emit the node in the printer.
81244          */
81245         function onEmitNode(hint, node, emitCallback) {
81246             // If we need to support substitutions for `super` in an async method,
81247             // we should track it here.
81248             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81249                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81250                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81251                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81252                     enclosingSuperContainerFlags = superContainerFlags;
81253                     previousOnEmitNode(hint, node, emitCallback);
81254                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81255                     return;
81256                 }
81257             }
81258             // Disable substitution in the generated super accessor itself.
81259             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81260                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81261                 enclosingSuperContainerFlags = 0;
81262                 previousOnEmitNode(hint, node, emitCallback);
81263                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81264                 return;
81265             }
81266             previousOnEmitNode(hint, node, emitCallback);
81267         }
81268         /**
81269          * Hooks node substitutions.
81270          *
81271          * @param hint A hint as to the intended usage of the node.
81272          * @param node The node to substitute.
81273          */
81274         function onSubstituteNode(hint, node) {
81275             node = previousOnSubstituteNode(hint, node);
81276             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81277                 return substituteExpression(node);
81278             }
81279             return node;
81280         }
81281         function substituteExpression(node) {
81282             switch (node.kind) {
81283                 case 194 /* PropertyAccessExpression */:
81284                     return substitutePropertyAccessExpression(node);
81285                 case 195 /* ElementAccessExpression */:
81286                     return substituteElementAccessExpression(node);
81287                 case 196 /* CallExpression */:
81288                     return substituteCallExpression(node);
81289             }
81290             return node;
81291         }
81292         function substitutePropertyAccessExpression(node) {
81293             if (node.expression.kind === 102 /* SuperKeyword */) {
81294                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81295             }
81296             return node;
81297         }
81298         function substituteElementAccessExpression(node) {
81299             if (node.expression.kind === 102 /* SuperKeyword */) {
81300                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81301             }
81302             return node;
81303         }
81304         function substituteCallExpression(node) {
81305             var expression = node.expression;
81306             if (ts.isSuperProperty(expression)) {
81307                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81308                     ? substitutePropertyAccessExpression(expression)
81309                     : substituteElementAccessExpression(expression);
81310                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81311                 /*typeArguments*/ undefined, __spreadArrays([
81312                     ts.createThis()
81313                 ], node.arguments));
81314             }
81315             return node;
81316         }
81317         function isSuperContainer(node) {
81318             var kind = node.kind;
81319             return kind === 245 /* ClassDeclaration */
81320                 || kind === 162 /* Constructor */
81321                 || kind === 161 /* MethodDeclaration */
81322                 || kind === 163 /* GetAccessor */
81323                 || kind === 164 /* SetAccessor */;
81324         }
81325         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81326             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81327                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81328                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81329             }
81330             else {
81331                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81332                 /*typeArguments*/ undefined, [argumentExpression]), location);
81333             }
81334         }
81335     }
81336     ts.transformES2017 = transformES2017;
81337     /** Creates a variable named `_super` with accessor properties for the given property names. */
81338     function createSuperAccessVariableStatement(resolver, node, names) {
81339         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81340         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81341         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81342         var accessors = [];
81343         names.forEach(function (_, key) {
81344             var name = ts.unescapeLeadingUnderscores(key);
81345             var getterAndSetter = [];
81346             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81347             /* modifiers */ undefined, 
81348             /* typeParameters */ undefined, 
81349             /* parameters */ [], 
81350             /* type */ undefined, 
81351             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81352             if (hasBinding) {
81353                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81354                 /* modifiers */ undefined, 
81355                 /* typeParameters */ undefined, 
81356                 /* parameters */ [
81357                     ts.createParameter(
81358                     /* decorators */ undefined, 
81359                     /* modifiers */ undefined, 
81360                     /* dotDotDotToken */ undefined, "v", 
81361                     /* questionToken */ undefined, 
81362                     /* type */ undefined, 
81363                     /* initializer */ undefined)
81364                 ], 
81365                 /* type */ undefined, 
81366                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81367             }
81368             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81369         });
81370         return ts.createVariableStatement(
81371         /* modifiers */ undefined, ts.createVariableDeclarationList([
81372             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81373             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81374             /* typeArguments */ undefined, [
81375                 ts.createNull(),
81376                 ts.createObjectLiteral(accessors, /* multiline */ true)
81377             ]))
81378         ], 2 /* Const */));
81379     }
81380     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81381     ts.awaiterHelper = {
81382         name: "typescript:awaiter",
81383         importName: "__awaiter",
81384         scoped: false,
81385         priority: 5,
81386         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            };"
81387     };
81388     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81389         context.requestEmitHelper(ts.awaiterHelper);
81390         var generatorFunc = ts.createFunctionExpression(
81391         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81392         /*name*/ undefined, 
81393         /*typeParameters*/ undefined, 
81394         /*parameters*/ [], 
81395         /*type*/ undefined, body);
81396         // Mark this node as originally an async function
81397         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81398         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81399         /*typeArguments*/ undefined, [
81400             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81401             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81402             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81403             generatorFunc
81404         ]);
81405     }
81406     ts.asyncSuperHelper = {
81407         name: "typescript:async-super",
81408         scoped: true,
81409         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81410     };
81411     ts.advancedAsyncSuperHelper = {
81412         name: "typescript:advanced-async-super",
81413         scoped: true,
81414         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")
81415     };
81416 })(ts || (ts = {}));
81417 /*@internal*/
81418 var ts;
81419 (function (ts) {
81420     var ESNextSubstitutionFlags;
81421     (function (ESNextSubstitutionFlags) {
81422         /** Enables substitutions for async methods with `super` calls. */
81423         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81424     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81425     // Facts we track as we traverse the tree
81426     var HierarchyFacts;
81427     (function (HierarchyFacts) {
81428         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81429         //
81430         // Ancestor facts
81431         //
81432         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81433         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81434         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81435         //
81436         // Ancestor masks
81437         //
81438         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81439         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81440         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81441         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81442         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81443         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81444         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81445         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81446         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81447         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81448     })(HierarchyFacts || (HierarchyFacts = {}));
81449     function transformES2018(context) {
81450         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81451         var resolver = context.getEmitResolver();
81452         var compilerOptions = context.getCompilerOptions();
81453         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81454         var previousOnEmitNode = context.onEmitNode;
81455         context.onEmitNode = onEmitNode;
81456         var previousOnSubstituteNode = context.onSubstituteNode;
81457         context.onSubstituteNode = onSubstituteNode;
81458         var exportedVariableStatement = false;
81459         var enabledSubstitutions;
81460         var enclosingFunctionFlags;
81461         var enclosingSuperContainerFlags = 0;
81462         var hierarchyFacts = 0;
81463         var currentSourceFile;
81464         var taggedTemplateStringDeclarations;
81465         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81466         var capturedSuperProperties;
81467         /** Whether the async function contains an element access on super (`super[x]`). */
81468         var hasSuperElementAccess;
81469         /** A set of node IDs for generated super accessors. */
81470         var substitutedSuperAccessors = [];
81471         return ts.chainBundle(transformSourceFile);
81472         function affectsSubtree(excludeFacts, includeFacts) {
81473             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81474         }
81475         /**
81476          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81477          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81478          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81479          */
81480         function enterSubtree(excludeFacts, includeFacts) {
81481             var ancestorFacts = hierarchyFacts;
81482             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81483             return ancestorFacts;
81484         }
81485         /**
81486          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81487          * subtree.
81488          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81489          */
81490         function exitSubtree(ancestorFacts) {
81491             hierarchyFacts = ancestorFacts;
81492         }
81493         function recordTaggedTemplateString(temp) {
81494             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81495         }
81496         function transformSourceFile(node) {
81497             if (node.isDeclarationFile) {
81498                 return node;
81499             }
81500             currentSourceFile = node;
81501             var visited = visitSourceFile(node);
81502             ts.addEmitHelpers(visited, context.readEmitHelpers());
81503             currentSourceFile = undefined;
81504             taggedTemplateStringDeclarations = undefined;
81505             return visited;
81506         }
81507         function visitor(node) {
81508             return visitorWorker(node, /*noDestructuringValue*/ false);
81509         }
81510         function visitorNoDestructuringValue(node) {
81511             return visitorWorker(node, /*noDestructuringValue*/ true);
81512         }
81513         function visitorNoAsyncModifier(node) {
81514             if (node.kind === 126 /* AsyncKeyword */) {
81515                 return undefined;
81516             }
81517             return node;
81518         }
81519         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81520             if (affectsSubtree(excludeFacts, includeFacts)) {
81521                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81522                 var result = cb(value);
81523                 exitSubtree(ancestorFacts);
81524                 return result;
81525             }
81526             return cb(value);
81527         }
81528         function visitDefault(node) {
81529             return ts.visitEachChild(node, visitor, context);
81530         }
81531         function visitorWorker(node, noDestructuringValue) {
81532             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81533                 return node;
81534             }
81535             switch (node.kind) {
81536                 case 206 /* AwaitExpression */:
81537                     return visitAwaitExpression(node);
81538                 case 212 /* YieldExpression */:
81539                     return visitYieldExpression(node);
81540                 case 235 /* ReturnStatement */:
81541                     return visitReturnStatement(node);
81542                 case 238 /* LabeledStatement */:
81543                     return visitLabeledStatement(node);
81544                 case 193 /* ObjectLiteralExpression */:
81545                     return visitObjectLiteralExpression(node);
81546                 case 209 /* BinaryExpression */:
81547                     return visitBinaryExpression(node, noDestructuringValue);
81548                 case 280 /* CatchClause */:
81549                     return visitCatchClause(node);
81550                 case 225 /* VariableStatement */:
81551                     return visitVariableStatement(node);
81552                 case 242 /* VariableDeclaration */:
81553                     return visitVariableDeclaration(node);
81554                 case 228 /* DoStatement */:
81555                 case 229 /* WhileStatement */:
81556                 case 231 /* ForInStatement */:
81557                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81558                 case 232 /* ForOfStatement */:
81559                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81560                 case 230 /* ForStatement */:
81561                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81562                 case 205 /* VoidExpression */:
81563                     return visitVoidExpression(node);
81564                 case 162 /* Constructor */:
81565                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81566                 case 161 /* MethodDeclaration */:
81567                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81568                 case 163 /* GetAccessor */:
81569                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81570                 case 164 /* SetAccessor */:
81571                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81572                 case 244 /* FunctionDeclaration */:
81573                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81574                 case 201 /* FunctionExpression */:
81575                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81576                 case 202 /* ArrowFunction */:
81577                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81578                 case 156 /* Parameter */:
81579                     return visitParameter(node);
81580                 case 226 /* ExpressionStatement */:
81581                     return visitExpressionStatement(node);
81582                 case 200 /* ParenthesizedExpression */:
81583                     return visitParenthesizedExpression(node, noDestructuringValue);
81584                 case 198 /* TaggedTemplateExpression */:
81585                     return visitTaggedTemplateExpression(node);
81586                 case 194 /* PropertyAccessExpression */:
81587                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81588                         capturedSuperProperties.set(node.name.escapedText, true);
81589                     }
81590                     return ts.visitEachChild(node, visitor, context);
81591                 case 195 /* ElementAccessExpression */:
81592                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81593                         hasSuperElementAccess = true;
81594                     }
81595                     return ts.visitEachChild(node, visitor, context);
81596                 case 245 /* ClassDeclaration */:
81597                 case 214 /* ClassExpression */:
81598                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81599                 default:
81600                     return ts.visitEachChild(node, visitor, context);
81601             }
81602         }
81603         function visitAwaitExpression(node) {
81604             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81605                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81606                 /*location*/ node), node);
81607             }
81608             return ts.visitEachChild(node, visitor, context);
81609         }
81610         function visitYieldExpression(node) {
81611             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81612                 if (node.asteriskToken) {
81613                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81614                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81615                 }
81616                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81617                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81618                     : ts.createVoidZero())), node), node);
81619             }
81620             return ts.visitEachChild(node, visitor, context);
81621         }
81622         function visitReturnStatement(node) {
81623             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81624                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81625             }
81626             return ts.visitEachChild(node, visitor, context);
81627         }
81628         function visitLabeledStatement(node) {
81629             if (enclosingFunctionFlags & 2 /* Async */) {
81630                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81631                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81632                     return visitForOfStatement(statement, node);
81633                 }
81634                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81635             }
81636             return ts.visitEachChild(node, visitor, context);
81637         }
81638         function chunkObjectLiteralElements(elements) {
81639             var chunkObject;
81640             var objects = [];
81641             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81642                 var e = elements_4[_i];
81643                 if (e.kind === 283 /* SpreadAssignment */) {
81644                     if (chunkObject) {
81645                         objects.push(ts.createObjectLiteral(chunkObject));
81646                         chunkObject = undefined;
81647                     }
81648                     var target = e.expression;
81649                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81650                 }
81651                 else {
81652                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81653                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81654                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81655                 }
81656             }
81657             if (chunkObject) {
81658                 objects.push(ts.createObjectLiteral(chunkObject));
81659             }
81660             return objects;
81661         }
81662         function visitObjectLiteralExpression(node) {
81663             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81664                 // spread elements emit like so:
81665                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81666                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81667                 // If the first element is a spread element, then the first argument to __assign is {}:
81668                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81669                 //
81670                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81671                 // example:
81672                 //      var k = { a: 1, b: 2 };
81673                 //      var o = { a: 3, ...k, b: k.a++ };
81674                 //      // expected: { a: 1, b: 1 }
81675                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81676                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81677                 //
81678                 // This also occurs for spread elements, not just property assignments:
81679                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81680                 //      var l = { c: 3 };
81681                 //      var o = { ...k, ...l };
81682                 //      // expected: { a: 1, b: 2, z: 9 }
81683                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81684                 // end up with `{ a: 1, b: 2, c: 3 }`
81685                 var objects = chunkObjectLiteralElements(node.properties);
81686                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81687                     objects.unshift(ts.createObjectLiteral());
81688                 }
81689                 var expression = objects[0];
81690                 if (objects.length > 1) {
81691                     for (var i = 1; i < objects.length; i++) {
81692                         expression = createAssignHelper(context, [expression, objects[i]]);
81693                     }
81694                     return expression;
81695                 }
81696                 else {
81697                     return createAssignHelper(context, objects);
81698                 }
81699             }
81700             return ts.visitEachChild(node, visitor, context);
81701         }
81702         function visitExpressionStatement(node) {
81703             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81704         }
81705         function visitParenthesizedExpression(node, noDestructuringValue) {
81706             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81707         }
81708         function visitSourceFile(node) {
81709             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81710                 0 /* StrictModeSourceFileIncludes */ :
81711                 1 /* SourceFileIncludes */);
81712             exportedVariableStatement = false;
81713             var visited = ts.visitEachChild(node, visitor, context);
81714             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81715                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81716             ]);
81717             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81718             exitSubtree(ancestorFacts);
81719             return result;
81720         }
81721         function visitTaggedTemplateExpression(node) {
81722             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81723         }
81724         /**
81725          * Visits a BinaryExpression that contains a destructuring assignment.
81726          *
81727          * @param node A BinaryExpression node.
81728          */
81729         function visitBinaryExpression(node, noDestructuringValue) {
81730             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81731                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81732             }
81733             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81734                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81735             }
81736             return ts.visitEachChild(node, visitor, context);
81737         }
81738         function visitCatchClause(node) {
81739             if (node.variableDeclaration &&
81740                 ts.isBindingPattern(node.variableDeclaration.name) &&
81741                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81742                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81743                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81744                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81745                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81746                 if (ts.some(visitedBindings)) {
81747                     block = ts.updateBlock(block, __spreadArrays([
81748                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81749                     ], block.statements));
81750                 }
81751                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81752             }
81753             return ts.visitEachChild(node, visitor, context);
81754         }
81755         function visitVariableStatement(node) {
81756             if (ts.hasModifier(node, 1 /* Export */)) {
81757                 var savedExportedVariableStatement = exportedVariableStatement;
81758                 exportedVariableStatement = true;
81759                 var visited = ts.visitEachChild(node, visitor, context);
81760                 exportedVariableStatement = savedExportedVariableStatement;
81761                 return visited;
81762             }
81763             return ts.visitEachChild(node, visitor, context);
81764         }
81765         /**
81766          * Visits a VariableDeclaration node with a binding pattern.
81767          *
81768          * @param node A VariableDeclaration node.
81769          */
81770         function visitVariableDeclaration(node) {
81771             if (exportedVariableStatement) {
81772                 var savedExportedVariableStatement = exportedVariableStatement;
81773                 exportedVariableStatement = false;
81774                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81775                 exportedVariableStatement = savedExportedVariableStatement;
81776                 return visited;
81777             }
81778             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81779         }
81780         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81781             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81782             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81783                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81784                 /*rval*/ undefined, exportedVariableStatement);
81785             }
81786             return ts.visitEachChild(node, visitor, context);
81787         }
81788         function visitForStatement(node) {
81789             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));
81790         }
81791         function visitVoidExpression(node) {
81792             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81793         }
81794         /**
81795          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81796          *
81797          * @param node A ForOfStatement.
81798          */
81799         function visitForOfStatement(node, outermostLabeledStatement) {
81800             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81801             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81802                 node = transformForOfStatementWithObjectRest(node);
81803             }
81804             var result = node.awaitModifier ?
81805                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81806                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81807             exitSubtree(ancestorFacts);
81808             return result;
81809         }
81810         function transformForOfStatementWithObjectRest(node) {
81811             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81812             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81813                 var bodyLocation = void 0;
81814                 var statementsLocation = void 0;
81815                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81816                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81817                 if (ts.isBlock(node.statement)) {
81818                     ts.addRange(statements, node.statement.statements);
81819                     bodyLocation = node.statement;
81820                     statementsLocation = node.statement.statements;
81821                 }
81822                 else if (node.statement) {
81823                     ts.append(statements, node.statement);
81824                     bodyLocation = node.statement;
81825                     statementsLocation = node.statement;
81826                 }
81827                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
81828                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
81829                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81830                 /*multiLine*/ true), bodyLocation));
81831             }
81832             return node;
81833         }
81834         function convertForOfStatementHead(node, boundValue) {
81835             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
81836             var bodyLocation;
81837             var statementsLocation;
81838             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
81839             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
81840             if (ts.isBlock(statement)) {
81841                 ts.addRange(statements, statement.statements);
81842                 bodyLocation = statement;
81843                 statementsLocation = statement.statements;
81844             }
81845             else {
81846                 statements.push(statement);
81847             }
81848             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81849             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
81850         }
81851         function createDownlevelAwait(expression) {
81852             return enclosingFunctionFlags & 1 /* Generator */
81853                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
81854                 : ts.createAwait(expression);
81855         }
81856         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
81857             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81858             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81859             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81860             var errorRecord = ts.createUniqueName("e");
81861             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
81862             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
81863             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
81864             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
81865             var getDone = ts.createPropertyAccess(result, "done");
81866             var getValue = ts.createPropertyAccess(result, "value");
81867             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
81868             hoistVariableDeclaration(errorRecord);
81869             hoistVariableDeclaration(returnMethod);
81870             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
81871             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
81872                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
81873                 callValues;
81874             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
81875             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
81876                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
81877                 ts.createVariableDeclaration(result)
81878             ]), node.expression), 2097152 /* NoHoisting */), 
81879             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
81880             /*incrementor*/ undefined, 
81881             /*statement*/ convertForOfStatementHead(node, getValue)), 
81882             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
81883             return ts.createTry(ts.createBlock([
81884                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
81885             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
81886                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
81887                     ts.createPropertyAssignment("error", catchVariable)
81888                 ])))
81889             ]), 1 /* SingleLine */)), ts.createBlock([
81890                 ts.createTry(
81891                 /*tryBlock*/ ts.createBlock([
81892                     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 */)
81893                 ]), 
81894                 /*catchClause*/ undefined, 
81895                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
81896                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
81897                 ]), 1 /* SingleLine */))
81898             ]));
81899         }
81900         function visitParameter(node) {
81901             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81902                 // Binding patterns are converted into a generated name and are
81903                 // evaluated inside the function body.
81904                 return ts.updateParameter(node, 
81905                 /*decorators*/ undefined, 
81906                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
81907                 /*questionToken*/ undefined, 
81908                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81909             }
81910             return ts.visitEachChild(node, visitor, context);
81911         }
81912         function visitConstructorDeclaration(node) {
81913             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81914             enclosingFunctionFlags = 0 /* Normal */;
81915             var updated = ts.updateConstructor(node, 
81916             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81917             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81918             return updated;
81919         }
81920         function visitGetAccessorDeclaration(node) {
81921             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81922             enclosingFunctionFlags = 0 /* Normal */;
81923             var updated = ts.updateGetAccessor(node, 
81924             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
81925             /*type*/ undefined, transformFunctionBody(node));
81926             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81927             return updated;
81928         }
81929         function visitSetAccessorDeclaration(node) {
81930             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81931             enclosingFunctionFlags = 0 /* Normal */;
81932             var updated = ts.updateSetAccessor(node, 
81933             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81934             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81935             return updated;
81936         }
81937         function visitMethodDeclaration(node) {
81938             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81939             enclosingFunctionFlags = ts.getFunctionFlags(node);
81940             var updated = ts.updateMethod(node, 
81941             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81942                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81943                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81944                 ? undefined
81945                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
81946             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81947             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81948                 ? transformAsyncGeneratorFunctionBody(node)
81949                 : transformFunctionBody(node));
81950             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81951             return updated;
81952         }
81953         function visitFunctionDeclaration(node) {
81954             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81955             enclosingFunctionFlags = ts.getFunctionFlags(node);
81956             var updated = ts.updateFunctionDeclaration(node, 
81957             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81958                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81959                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81960                 ? undefined
81961                 : node.asteriskToken, node.name, 
81962             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81963             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81964                 ? transformAsyncGeneratorFunctionBody(node)
81965                 : transformFunctionBody(node));
81966             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81967             return updated;
81968         }
81969         function visitArrowFunction(node) {
81970             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81971             enclosingFunctionFlags = ts.getFunctionFlags(node);
81972             var updated = ts.updateArrowFunction(node, node.modifiers, 
81973             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81974             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
81975             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81976             return updated;
81977         }
81978         function visitFunctionExpression(node) {
81979             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81980             enclosingFunctionFlags = ts.getFunctionFlags(node);
81981             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
81982                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81983                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81984                 ? undefined
81985                 : node.asteriskToken, node.name, 
81986             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81987             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81988                 ? transformAsyncGeneratorFunctionBody(node)
81989                 : transformFunctionBody(node));
81990             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81991             return updated;
81992         }
81993         function transformAsyncGeneratorFunctionBody(node) {
81994             resumeLexicalEnvironment();
81995             var statements = [];
81996             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81997             appendObjectRestAssignmentsIfNeeded(statements, node);
81998             var savedCapturedSuperProperties = capturedSuperProperties;
81999             var savedHasSuperElementAccess = hasSuperElementAccess;
82000             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82001             hasSuperElementAccess = false;
82002             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82003             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82004             /*typeParameters*/ undefined, 
82005             /*parameters*/ [], 
82006             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82007             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82008             // This step isn't needed if we eventually transform this to ES5.
82009             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82010             if (emitSuperHelpers) {
82011                 enableSubstitutionForAsyncMethodsWithSuper();
82012                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82013                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82014                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82015             }
82016             statements.push(returnStatement);
82017             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82018             var block = ts.updateBlock(node.body, statements);
82019             if (emitSuperHelpers && hasSuperElementAccess) {
82020                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82021                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82022                 }
82023                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82024                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82025                 }
82026             }
82027             capturedSuperProperties = savedCapturedSuperProperties;
82028             hasSuperElementAccess = savedHasSuperElementAccess;
82029             return block;
82030         }
82031         function transformFunctionBody(node) {
82032             resumeLexicalEnvironment();
82033             var statementOffset = 0;
82034             var statements = [];
82035             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82036             if (ts.isBlock(body)) {
82037                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82038             }
82039             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82040             var leadingStatements = endLexicalEnvironment();
82041             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82042                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82043                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82044                 ts.addRange(statements, block.statements.slice(statementOffset));
82045                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82046             }
82047             return body;
82048         }
82049         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82050             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82051                 var parameter = _a[_i];
82052                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82053                     var temp = ts.getGeneratedNameForNode(parameter);
82054                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82055                     /*doNotRecordTempVariablesInLine*/ false, 
82056                     /*skipInitializer*/ true);
82057                     if (ts.some(declarations)) {
82058                         var statement = ts.createVariableStatement(
82059                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82060                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82061                         statements = ts.append(statements, statement);
82062                     }
82063                 }
82064             }
82065             return statements;
82066         }
82067         function enableSubstitutionForAsyncMethodsWithSuper() {
82068             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82069                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82070                 // We need to enable substitutions for call, property access, and element access
82071                 // if we need to rewrite super calls.
82072                 context.enableSubstitution(196 /* CallExpression */);
82073                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82074                 context.enableSubstitution(195 /* ElementAccessExpression */);
82075                 // We need to be notified when entering and exiting declarations that bind super.
82076                 context.enableEmitNotification(245 /* ClassDeclaration */);
82077                 context.enableEmitNotification(161 /* MethodDeclaration */);
82078                 context.enableEmitNotification(163 /* GetAccessor */);
82079                 context.enableEmitNotification(164 /* SetAccessor */);
82080                 context.enableEmitNotification(162 /* Constructor */);
82081                 // We need to be notified when entering the generated accessor arrow functions.
82082                 context.enableEmitNotification(225 /* VariableStatement */);
82083             }
82084         }
82085         /**
82086          * Called by the printer just before a node is printed.
82087          *
82088          * @param hint A hint as to the intended usage of the node.
82089          * @param node The node to be printed.
82090          * @param emitCallback The callback used to emit the node.
82091          */
82092         function onEmitNode(hint, node, emitCallback) {
82093             // If we need to support substitutions for `super` in an async method,
82094             // we should track it here.
82095             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82096                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82097                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82098                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82099                     enclosingSuperContainerFlags = superContainerFlags;
82100                     previousOnEmitNode(hint, node, emitCallback);
82101                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82102                     return;
82103                 }
82104             }
82105             // Disable substitution in the generated super accessor itself.
82106             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82107                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82108                 enclosingSuperContainerFlags = 0;
82109                 previousOnEmitNode(hint, node, emitCallback);
82110                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82111                 return;
82112             }
82113             previousOnEmitNode(hint, node, emitCallback);
82114         }
82115         /**
82116          * Hooks node substitutions.
82117          *
82118          * @param hint The context for the emitter.
82119          * @param node The node to substitute.
82120          */
82121         function onSubstituteNode(hint, node) {
82122             node = previousOnSubstituteNode(hint, node);
82123             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82124                 return substituteExpression(node);
82125             }
82126             return node;
82127         }
82128         function substituteExpression(node) {
82129             switch (node.kind) {
82130                 case 194 /* PropertyAccessExpression */:
82131                     return substitutePropertyAccessExpression(node);
82132                 case 195 /* ElementAccessExpression */:
82133                     return substituteElementAccessExpression(node);
82134                 case 196 /* CallExpression */:
82135                     return substituteCallExpression(node);
82136             }
82137             return node;
82138         }
82139         function substitutePropertyAccessExpression(node) {
82140             if (node.expression.kind === 102 /* SuperKeyword */) {
82141                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82142             }
82143             return node;
82144         }
82145         function substituteElementAccessExpression(node) {
82146             if (node.expression.kind === 102 /* SuperKeyword */) {
82147                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82148             }
82149             return node;
82150         }
82151         function substituteCallExpression(node) {
82152             var expression = node.expression;
82153             if (ts.isSuperProperty(expression)) {
82154                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82155                     ? substitutePropertyAccessExpression(expression)
82156                     : substituteElementAccessExpression(expression);
82157                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82158                 /*typeArguments*/ undefined, __spreadArrays([
82159                     ts.createThis()
82160                 ], node.arguments));
82161             }
82162             return node;
82163         }
82164         function isSuperContainer(node) {
82165             var kind = node.kind;
82166             return kind === 245 /* ClassDeclaration */
82167                 || kind === 162 /* Constructor */
82168                 || kind === 161 /* MethodDeclaration */
82169                 || kind === 163 /* GetAccessor */
82170                 || kind === 164 /* SetAccessor */;
82171         }
82172         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82173             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82174                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82175                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82176             }
82177             else {
82178                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82179                 /*typeArguments*/ undefined, [argumentExpression]), location);
82180             }
82181         }
82182     }
82183     ts.transformES2018 = transformES2018;
82184     ts.assignHelper = {
82185         name: "typescript:assign",
82186         importName: "__assign",
82187         scoped: false,
82188         priority: 1,
82189         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            };"
82190     };
82191     function createAssignHelper(context, attributesSegments) {
82192         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82193             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82194         }
82195         context.requestEmitHelper(ts.assignHelper);
82196         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82197         /*typeArguments*/ undefined, attributesSegments);
82198     }
82199     ts.createAssignHelper = createAssignHelper;
82200     ts.awaitHelper = {
82201         name: "typescript:await",
82202         importName: "__await",
82203         scoped: false,
82204         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82205     };
82206     function createAwaitHelper(context, expression) {
82207         context.requestEmitHelper(ts.awaitHelper);
82208         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82209     }
82210     ts.asyncGeneratorHelper = {
82211         name: "typescript:asyncGenerator",
82212         importName: "__asyncGenerator",
82213         scoped: false,
82214         dependencies: [ts.awaitHelper],
82215         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            };"
82216     };
82217     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82218         context.requestEmitHelper(ts.asyncGeneratorHelper);
82219         // Mark this node as originally an async function
82220         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82221         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82222         /*typeArguments*/ undefined, [
82223             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82224             ts.createIdentifier("arguments"),
82225             generatorFunc
82226         ]);
82227     }
82228     ts.asyncDelegator = {
82229         name: "typescript:asyncDelegator",
82230         importName: "__asyncDelegator",
82231         scoped: false,
82232         dependencies: [ts.awaitHelper],
82233         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            };"
82234     };
82235     function createAsyncDelegatorHelper(context, expression, location) {
82236         context.requestEmitHelper(ts.asyncDelegator);
82237         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82238         /*typeArguments*/ undefined, [expression]), location);
82239     }
82240     ts.asyncValues = {
82241         name: "typescript:asyncValues",
82242         importName: "__asyncValues",
82243         scoped: false,
82244         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            };"
82245     };
82246     function createAsyncValuesHelper(context, expression, location) {
82247         context.requestEmitHelper(ts.asyncValues);
82248         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82249         /*typeArguments*/ undefined, [expression]), location);
82250     }
82251 })(ts || (ts = {}));
82252 /*@internal*/
82253 var ts;
82254 (function (ts) {
82255     function transformES2019(context) {
82256         return ts.chainBundle(transformSourceFile);
82257         function transformSourceFile(node) {
82258             if (node.isDeclarationFile) {
82259                 return node;
82260             }
82261             return ts.visitEachChild(node, visitor, context);
82262         }
82263         function visitor(node) {
82264             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82265                 return node;
82266             }
82267             switch (node.kind) {
82268                 case 280 /* CatchClause */:
82269                     return visitCatchClause(node);
82270                 default:
82271                     return ts.visitEachChild(node, visitor, context);
82272             }
82273         }
82274         function visitCatchClause(node) {
82275             if (!node.variableDeclaration) {
82276                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82277             }
82278             return ts.visitEachChild(node, visitor, context);
82279         }
82280     }
82281     ts.transformES2019 = transformES2019;
82282 })(ts || (ts = {}));
82283 /*@internal*/
82284 var ts;
82285 (function (ts) {
82286     function transformES2020(context) {
82287         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82288         return ts.chainBundle(transformSourceFile);
82289         function transformSourceFile(node) {
82290             if (node.isDeclarationFile) {
82291                 return node;
82292             }
82293             return ts.visitEachChild(node, visitor, context);
82294         }
82295         function visitor(node) {
82296             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82297                 return node;
82298             }
82299             switch (node.kind) {
82300                 case 194 /* PropertyAccessExpression */:
82301                 case 195 /* ElementAccessExpression */:
82302                 case 196 /* CallExpression */:
82303                     if (node.flags & 32 /* OptionalChain */) {
82304                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82305                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82306                         return updated;
82307                     }
82308                     return ts.visitEachChild(node, visitor, context);
82309                 case 209 /* BinaryExpression */:
82310                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82311                         return transformNullishCoalescingExpression(node);
82312                     }
82313                     return ts.visitEachChild(node, visitor, context);
82314                 case 203 /* DeleteExpression */:
82315                     return visitDeleteExpression(node);
82316                 default:
82317                     return ts.visitEachChild(node, visitor, context);
82318             }
82319         }
82320         function flattenChain(chain) {
82321             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82322             var links = [chain];
82323             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82324                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82325                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82326                 links.unshift(chain);
82327             }
82328             return { expression: chain.expression, chain: links };
82329         }
82330         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82331             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82332             if (ts.isSyntheticReference(expression)) {
82333                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82334                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82335                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82336             }
82337             return ts.updateParen(node, expression);
82338         }
82339         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
82340             if (ts.isOptionalChain(node)) {
82341                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82342                 return visitOptionalExpression(node, captureThisArg, isDelete);
82343             }
82344             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82345             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82346             var thisArg;
82347             if (captureThisArg) {
82348                 if (shouldCaptureInTempVariable(expression)) {
82349                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82350                     expression = ts.createAssignment(thisArg, expression);
82351                     // if (inParameterInitializer) tempVariableInParameter = true;
82352                 }
82353                 else {
82354                     thisArg = expression;
82355                 }
82356             }
82357             expression = node.kind === 194 /* PropertyAccessExpression */
82358                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82359                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82360             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82361         }
82362         function visitNonOptionalCallExpression(node, captureThisArg) {
82363             if (ts.isOptionalChain(node)) {
82364                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82365                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82366             }
82367             return ts.visitEachChild(node, visitor, context);
82368         }
82369         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82370             switch (node.kind) {
82371                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82372                 case 194 /* PropertyAccessExpression */:
82373                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82374                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82375                 default: return ts.visitNode(node, visitor, ts.isExpression);
82376             }
82377         }
82378         function visitOptionalExpression(node, captureThisArg, isDelete) {
82379             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82380             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82381             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82382             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82383             var capturedLeft = leftExpression;
82384             if (shouldCaptureInTempVariable(leftExpression)) {
82385                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82386                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82387                 // if (inParameterInitializer) tempVariableInParameter = true;
82388             }
82389             var rightExpression = capturedLeft;
82390             var thisArg;
82391             for (var i = 0; i < chain.length; i++) {
82392                 var segment = chain[i];
82393                 switch (segment.kind) {
82394                     case 194 /* PropertyAccessExpression */:
82395                     case 195 /* ElementAccessExpression */:
82396                         if (i === chain.length - 1 && captureThisArg) {
82397                             if (shouldCaptureInTempVariable(rightExpression)) {
82398                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82399                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82400                                 // if (inParameterInitializer) tempVariableInParameter = true;
82401                             }
82402                             else {
82403                                 thisArg = rightExpression;
82404                             }
82405                         }
82406                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82407                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82408                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82409                         break;
82410                     case 196 /* CallExpression */:
82411                         if (i === 0 && leftThisArg) {
82412                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82413                         }
82414                         else {
82415                             rightExpression = ts.createCall(rightExpression, 
82416                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82417                         }
82418                         break;
82419                 }
82420                 ts.setOriginalNode(rightExpression, segment);
82421             }
82422             var target = isDelete
82423                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82424                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82425             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82426         }
82427         function createNotNullCondition(left, right, invert) {
82428             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()));
82429         }
82430         function transformNullishCoalescingExpression(node) {
82431             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82432             var right = left;
82433             if (shouldCaptureInTempVariable(left)) {
82434                 right = ts.createTempVariable(hoistVariableDeclaration);
82435                 left = ts.createAssignment(right, left);
82436                 // if (inParameterInitializer) tempVariableInParameter = true;
82437             }
82438             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82439         }
82440         function shouldCaptureInTempVariable(expression) {
82441             // don't capture identifiers and `this` in a temporary variable
82442             // `super` cannot be captured as it's no real variable
82443             return !ts.isIdentifier(expression) &&
82444                 expression.kind !== 104 /* ThisKeyword */ &&
82445                 expression.kind !== 102 /* SuperKeyword */;
82446         }
82447         function visitDeleteExpression(node) {
82448             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82449                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82450                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82451         }
82452     }
82453     ts.transformES2020 = transformES2020;
82454 })(ts || (ts = {}));
82455 /*@internal*/
82456 var ts;
82457 (function (ts) {
82458     function transformESNext(context) {
82459         return ts.chainBundle(transformSourceFile);
82460         function transformSourceFile(node) {
82461             if (node.isDeclarationFile) {
82462                 return node;
82463             }
82464             return ts.visitEachChild(node, visitor, context);
82465         }
82466         function visitor(node) {
82467             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82468                 return node;
82469             }
82470             switch (node.kind) {
82471                 default:
82472                     return ts.visitEachChild(node, visitor, context);
82473             }
82474         }
82475     }
82476     ts.transformESNext = transformESNext;
82477 })(ts || (ts = {}));
82478 /*@internal*/
82479 var ts;
82480 (function (ts) {
82481     function transformJsx(context) {
82482         var compilerOptions = context.getCompilerOptions();
82483         var currentSourceFile;
82484         return ts.chainBundle(transformSourceFile);
82485         /**
82486          * Transform JSX-specific syntax in a SourceFile.
82487          *
82488          * @param node A SourceFile node.
82489          */
82490         function transformSourceFile(node) {
82491             if (node.isDeclarationFile) {
82492                 return node;
82493             }
82494             currentSourceFile = node;
82495             var visited = ts.visitEachChild(node, visitor, context);
82496             ts.addEmitHelpers(visited, context.readEmitHelpers());
82497             return visited;
82498         }
82499         function visitor(node) {
82500             if (node.transformFlags & 2 /* ContainsJsx */) {
82501                 return visitorWorker(node);
82502             }
82503             else {
82504                 return node;
82505             }
82506         }
82507         function visitorWorker(node) {
82508             switch (node.kind) {
82509                 case 266 /* JsxElement */:
82510                     return visitJsxElement(node, /*isChild*/ false);
82511                 case 267 /* JsxSelfClosingElement */:
82512                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82513                 case 270 /* JsxFragment */:
82514                     return visitJsxFragment(node, /*isChild*/ false);
82515                 case 276 /* JsxExpression */:
82516                     return visitJsxExpression(node);
82517                 default:
82518                     return ts.visitEachChild(node, visitor, context);
82519             }
82520         }
82521         function transformJsxChildToExpression(node) {
82522             switch (node.kind) {
82523                 case 11 /* JsxText */:
82524                     return visitJsxText(node);
82525                 case 276 /* JsxExpression */:
82526                     return visitJsxExpression(node);
82527                 case 266 /* JsxElement */:
82528                     return visitJsxElement(node, /*isChild*/ true);
82529                 case 267 /* JsxSelfClosingElement */:
82530                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82531                 case 270 /* JsxFragment */:
82532                     return visitJsxFragment(node, /*isChild*/ true);
82533                 default:
82534                     return ts.Debug.failBadSyntaxKind(node);
82535             }
82536         }
82537         function visitJsxElement(node, isChild) {
82538             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82539         }
82540         function visitJsxSelfClosingElement(node, isChild) {
82541             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82542         }
82543         function visitJsxFragment(node, isChild) {
82544             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82545         }
82546         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82547             var tagName = getTagName(node);
82548             var objectProperties;
82549             var attrs = node.attributes.properties;
82550             if (attrs.length === 0) {
82551                 // When there are no attributes, React wants "null"
82552                 objectProperties = ts.createNull();
82553             }
82554             else {
82555                 // Map spans of JsxAttribute nodes into object literals and spans
82556                 // of JsxSpreadAttribute nodes into expressions.
82557                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82558                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82559                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82560                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82561                     // We must always emit at least one object literal before a spread
82562                     // argument.
82563                     segments.unshift(ts.createObjectLiteral());
82564                 }
82565                 // Either emit one big object literal (no spread attribs), or
82566                 // a call to the __assign helper.
82567                 objectProperties = ts.singleOrUndefined(segments);
82568                 if (!objectProperties) {
82569                     objectProperties = ts.createAssignHelper(context, segments);
82570                 }
82571             }
82572             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82573             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82574             if (isChild) {
82575                 ts.startOnNewLine(element);
82576             }
82577             return element;
82578         }
82579         function visitJsxOpeningFragment(node, children, isChild, location) {
82580             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82581             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82582             if (isChild) {
82583                 ts.startOnNewLine(element);
82584             }
82585             return element;
82586         }
82587         function transformJsxSpreadAttributeToExpression(node) {
82588             return ts.visitNode(node.expression, visitor, ts.isExpression);
82589         }
82590         function transformJsxAttributeToObjectLiteralElement(node) {
82591             var name = getAttributeName(node);
82592             var expression = transformJsxAttributeInitializer(node.initializer);
82593             return ts.createPropertyAssignment(name, expression);
82594         }
82595         function transformJsxAttributeInitializer(node) {
82596             if (node === undefined) {
82597                 return ts.createTrue();
82598             }
82599             else if (node.kind === 10 /* StringLiteral */) {
82600                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82601                 // Need to be escaped to be handled correctly in a normal string
82602                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82603                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82604                 return ts.setTextRange(literal, node);
82605             }
82606             else if (node.kind === 276 /* JsxExpression */) {
82607                 if (node.expression === undefined) {
82608                     return ts.createTrue();
82609                 }
82610                 return visitJsxExpression(node);
82611             }
82612             else {
82613                 return ts.Debug.failBadSyntaxKind(node);
82614             }
82615         }
82616         function visitJsxText(node) {
82617             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82618             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82619         }
82620         /**
82621          * JSX trims whitespace at the end and beginning of lines, except that the
82622          * start/end of a tag is considered a start/end of a line only if that line is
82623          * on the same line as the closing tag. See examples in
82624          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82625          * 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
82626          *
82627          * An equivalent algorithm would be:
82628          * - If there is only one line, return it.
82629          * - If there is only whitespace (but multiple lines), return `undefined`.
82630          * - Split the text into lines.
82631          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82632          * - Decode entities on each line (individually).
82633          * - Remove empty lines and join the rest with " ".
82634          */
82635         function fixupWhitespaceAndDecodeEntities(text) {
82636             var acc;
82637             // First non-whitespace character on this line.
82638             var firstNonWhitespace = 0;
82639             // Last non-whitespace character on this line.
82640             var lastNonWhitespace = -1;
82641             // These initial values are special because the first line is:
82642             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82643             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82644             for (var i = 0; i < text.length; i++) {
82645                 var c = text.charCodeAt(i);
82646                 if (ts.isLineBreak(c)) {
82647                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82648                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82649                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82650                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82651                     }
82652                     // Reset firstNonWhitespace for the next line.
82653                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82654                     firstNonWhitespace = -1;
82655                 }
82656                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82657                     lastNonWhitespace = i;
82658                     if (firstNonWhitespace === -1) {
82659                         firstNonWhitespace = i;
82660                     }
82661                 }
82662             }
82663             return firstNonWhitespace !== -1
82664                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82665                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82666                 // Last line was all whitespace, so ignore it
82667                 : acc;
82668         }
82669         function addLineOfJsxText(acc, trimmedLine) {
82670             // We do not escape the string here as that is handled by the printer
82671             // when it emits the literal. We do, however, need to decode JSX entities.
82672             var decoded = decodeEntities(trimmedLine);
82673             return acc === undefined ? decoded : acc + " " + decoded;
82674         }
82675         /**
82676          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82677          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82678          */
82679         function decodeEntities(text) {
82680             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82681                 if (decimal) {
82682                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82683                 }
82684                 else if (hex) {
82685                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82686                 }
82687                 else {
82688                     var ch = entities.get(word);
82689                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82690                     return ch ? ts.utf16EncodeAsString(ch) : match;
82691                 }
82692             });
82693         }
82694         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82695         function tryDecodeEntities(text) {
82696             var decoded = decodeEntities(text);
82697             return decoded === text ? undefined : decoded;
82698         }
82699         function getTagName(node) {
82700             if (node.kind === 266 /* JsxElement */) {
82701                 return getTagName(node.openingElement);
82702             }
82703             else {
82704                 var name = node.tagName;
82705                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82706                     return ts.createLiteral(ts.idText(name));
82707                 }
82708                 else {
82709                     return ts.createExpressionFromEntityName(name);
82710                 }
82711             }
82712         }
82713         /**
82714          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82715          * these emit into an object literal property name, we don't need to be worried
82716          * about keywords, just non-identifier characters
82717          */
82718         function getAttributeName(node) {
82719             var name = node.name;
82720             var text = ts.idText(name);
82721             if (/^[A-Za-z_]\w*$/.test(text)) {
82722                 return name;
82723             }
82724             else {
82725                 return ts.createLiteral(text);
82726             }
82727         }
82728         function visitJsxExpression(node) {
82729             return ts.visitNode(node.expression, visitor, ts.isExpression);
82730         }
82731     }
82732     ts.transformJsx = transformJsx;
82733     var entities = ts.createMapFromTemplate({
82734         quot: 0x0022,
82735         amp: 0x0026,
82736         apos: 0x0027,
82737         lt: 0x003C,
82738         gt: 0x003E,
82739         nbsp: 0x00A0,
82740         iexcl: 0x00A1,
82741         cent: 0x00A2,
82742         pound: 0x00A3,
82743         curren: 0x00A4,
82744         yen: 0x00A5,
82745         brvbar: 0x00A6,
82746         sect: 0x00A7,
82747         uml: 0x00A8,
82748         copy: 0x00A9,
82749         ordf: 0x00AA,
82750         laquo: 0x00AB,
82751         not: 0x00AC,
82752         shy: 0x00AD,
82753         reg: 0x00AE,
82754         macr: 0x00AF,
82755         deg: 0x00B0,
82756         plusmn: 0x00B1,
82757         sup2: 0x00B2,
82758         sup3: 0x00B3,
82759         acute: 0x00B4,
82760         micro: 0x00B5,
82761         para: 0x00B6,
82762         middot: 0x00B7,
82763         cedil: 0x00B8,
82764         sup1: 0x00B9,
82765         ordm: 0x00BA,
82766         raquo: 0x00BB,
82767         frac14: 0x00BC,
82768         frac12: 0x00BD,
82769         frac34: 0x00BE,
82770         iquest: 0x00BF,
82771         Agrave: 0x00C0,
82772         Aacute: 0x00C1,
82773         Acirc: 0x00C2,
82774         Atilde: 0x00C3,
82775         Auml: 0x00C4,
82776         Aring: 0x00C5,
82777         AElig: 0x00C6,
82778         Ccedil: 0x00C7,
82779         Egrave: 0x00C8,
82780         Eacute: 0x00C9,
82781         Ecirc: 0x00CA,
82782         Euml: 0x00CB,
82783         Igrave: 0x00CC,
82784         Iacute: 0x00CD,
82785         Icirc: 0x00CE,
82786         Iuml: 0x00CF,
82787         ETH: 0x00D0,
82788         Ntilde: 0x00D1,
82789         Ograve: 0x00D2,
82790         Oacute: 0x00D3,
82791         Ocirc: 0x00D4,
82792         Otilde: 0x00D5,
82793         Ouml: 0x00D6,
82794         times: 0x00D7,
82795         Oslash: 0x00D8,
82796         Ugrave: 0x00D9,
82797         Uacute: 0x00DA,
82798         Ucirc: 0x00DB,
82799         Uuml: 0x00DC,
82800         Yacute: 0x00DD,
82801         THORN: 0x00DE,
82802         szlig: 0x00DF,
82803         agrave: 0x00E0,
82804         aacute: 0x00E1,
82805         acirc: 0x00E2,
82806         atilde: 0x00E3,
82807         auml: 0x00E4,
82808         aring: 0x00E5,
82809         aelig: 0x00E6,
82810         ccedil: 0x00E7,
82811         egrave: 0x00E8,
82812         eacute: 0x00E9,
82813         ecirc: 0x00EA,
82814         euml: 0x00EB,
82815         igrave: 0x00EC,
82816         iacute: 0x00ED,
82817         icirc: 0x00EE,
82818         iuml: 0x00EF,
82819         eth: 0x00F0,
82820         ntilde: 0x00F1,
82821         ograve: 0x00F2,
82822         oacute: 0x00F3,
82823         ocirc: 0x00F4,
82824         otilde: 0x00F5,
82825         ouml: 0x00F6,
82826         divide: 0x00F7,
82827         oslash: 0x00F8,
82828         ugrave: 0x00F9,
82829         uacute: 0x00FA,
82830         ucirc: 0x00FB,
82831         uuml: 0x00FC,
82832         yacute: 0x00FD,
82833         thorn: 0x00FE,
82834         yuml: 0x00FF,
82835         OElig: 0x0152,
82836         oelig: 0x0153,
82837         Scaron: 0x0160,
82838         scaron: 0x0161,
82839         Yuml: 0x0178,
82840         fnof: 0x0192,
82841         circ: 0x02C6,
82842         tilde: 0x02DC,
82843         Alpha: 0x0391,
82844         Beta: 0x0392,
82845         Gamma: 0x0393,
82846         Delta: 0x0394,
82847         Epsilon: 0x0395,
82848         Zeta: 0x0396,
82849         Eta: 0x0397,
82850         Theta: 0x0398,
82851         Iota: 0x0399,
82852         Kappa: 0x039A,
82853         Lambda: 0x039B,
82854         Mu: 0x039C,
82855         Nu: 0x039D,
82856         Xi: 0x039E,
82857         Omicron: 0x039F,
82858         Pi: 0x03A0,
82859         Rho: 0x03A1,
82860         Sigma: 0x03A3,
82861         Tau: 0x03A4,
82862         Upsilon: 0x03A5,
82863         Phi: 0x03A6,
82864         Chi: 0x03A7,
82865         Psi: 0x03A8,
82866         Omega: 0x03A9,
82867         alpha: 0x03B1,
82868         beta: 0x03B2,
82869         gamma: 0x03B3,
82870         delta: 0x03B4,
82871         epsilon: 0x03B5,
82872         zeta: 0x03B6,
82873         eta: 0x03B7,
82874         theta: 0x03B8,
82875         iota: 0x03B9,
82876         kappa: 0x03BA,
82877         lambda: 0x03BB,
82878         mu: 0x03BC,
82879         nu: 0x03BD,
82880         xi: 0x03BE,
82881         omicron: 0x03BF,
82882         pi: 0x03C0,
82883         rho: 0x03C1,
82884         sigmaf: 0x03C2,
82885         sigma: 0x03C3,
82886         tau: 0x03C4,
82887         upsilon: 0x03C5,
82888         phi: 0x03C6,
82889         chi: 0x03C7,
82890         psi: 0x03C8,
82891         omega: 0x03C9,
82892         thetasym: 0x03D1,
82893         upsih: 0x03D2,
82894         piv: 0x03D6,
82895         ensp: 0x2002,
82896         emsp: 0x2003,
82897         thinsp: 0x2009,
82898         zwnj: 0x200C,
82899         zwj: 0x200D,
82900         lrm: 0x200E,
82901         rlm: 0x200F,
82902         ndash: 0x2013,
82903         mdash: 0x2014,
82904         lsquo: 0x2018,
82905         rsquo: 0x2019,
82906         sbquo: 0x201A,
82907         ldquo: 0x201C,
82908         rdquo: 0x201D,
82909         bdquo: 0x201E,
82910         dagger: 0x2020,
82911         Dagger: 0x2021,
82912         bull: 0x2022,
82913         hellip: 0x2026,
82914         permil: 0x2030,
82915         prime: 0x2032,
82916         Prime: 0x2033,
82917         lsaquo: 0x2039,
82918         rsaquo: 0x203A,
82919         oline: 0x203E,
82920         frasl: 0x2044,
82921         euro: 0x20AC,
82922         image: 0x2111,
82923         weierp: 0x2118,
82924         real: 0x211C,
82925         trade: 0x2122,
82926         alefsym: 0x2135,
82927         larr: 0x2190,
82928         uarr: 0x2191,
82929         rarr: 0x2192,
82930         darr: 0x2193,
82931         harr: 0x2194,
82932         crarr: 0x21B5,
82933         lArr: 0x21D0,
82934         uArr: 0x21D1,
82935         rArr: 0x21D2,
82936         dArr: 0x21D3,
82937         hArr: 0x21D4,
82938         forall: 0x2200,
82939         part: 0x2202,
82940         exist: 0x2203,
82941         empty: 0x2205,
82942         nabla: 0x2207,
82943         isin: 0x2208,
82944         notin: 0x2209,
82945         ni: 0x220B,
82946         prod: 0x220F,
82947         sum: 0x2211,
82948         minus: 0x2212,
82949         lowast: 0x2217,
82950         radic: 0x221A,
82951         prop: 0x221D,
82952         infin: 0x221E,
82953         ang: 0x2220,
82954         and: 0x2227,
82955         or: 0x2228,
82956         cap: 0x2229,
82957         cup: 0x222A,
82958         int: 0x222B,
82959         there4: 0x2234,
82960         sim: 0x223C,
82961         cong: 0x2245,
82962         asymp: 0x2248,
82963         ne: 0x2260,
82964         equiv: 0x2261,
82965         le: 0x2264,
82966         ge: 0x2265,
82967         sub: 0x2282,
82968         sup: 0x2283,
82969         nsub: 0x2284,
82970         sube: 0x2286,
82971         supe: 0x2287,
82972         oplus: 0x2295,
82973         otimes: 0x2297,
82974         perp: 0x22A5,
82975         sdot: 0x22C5,
82976         lceil: 0x2308,
82977         rceil: 0x2309,
82978         lfloor: 0x230A,
82979         rfloor: 0x230B,
82980         lang: 0x2329,
82981         rang: 0x232A,
82982         loz: 0x25CA,
82983         spades: 0x2660,
82984         clubs: 0x2663,
82985         hearts: 0x2665,
82986         diams: 0x2666
82987     });
82988 })(ts || (ts = {}));
82989 /*@internal*/
82990 var ts;
82991 (function (ts) {
82992     function transformES2016(context) {
82993         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82994         return ts.chainBundle(transformSourceFile);
82995         function transformSourceFile(node) {
82996             if (node.isDeclarationFile) {
82997                 return node;
82998             }
82999             return ts.visitEachChild(node, visitor, context);
83000         }
83001         function visitor(node) {
83002             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83003                 return node;
83004             }
83005             switch (node.kind) {
83006                 case 209 /* BinaryExpression */:
83007                     return visitBinaryExpression(node);
83008                 default:
83009                     return ts.visitEachChild(node, visitor, context);
83010             }
83011         }
83012         function visitBinaryExpression(node) {
83013             switch (node.operatorToken.kind) {
83014                 case 66 /* AsteriskAsteriskEqualsToken */:
83015                     return visitExponentiationAssignmentExpression(node);
83016                 case 42 /* AsteriskAsteriskToken */:
83017                     return visitExponentiationExpression(node);
83018                 default:
83019                     return ts.visitEachChild(node, visitor, context);
83020             }
83021         }
83022         function visitExponentiationAssignmentExpression(node) {
83023             var target;
83024             var value;
83025             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83026             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83027             if (ts.isElementAccessExpression(left)) {
83028                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83029                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83030                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83031                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83032                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83033             }
83034             else if (ts.isPropertyAccessExpression(left)) {
83035                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83036                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83037                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83038                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83039             }
83040             else {
83041                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83042                 target = left;
83043                 value = left;
83044             }
83045             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83046         }
83047         function visitExponentiationExpression(node) {
83048             // Transforms `a ** b` into `Math.pow(a, b)`
83049             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83050             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83051             return ts.createMathPow(left, right, /*location*/ node);
83052         }
83053     }
83054     ts.transformES2016 = transformES2016;
83055 })(ts || (ts = {}));
83056 /*@internal*/
83057 var ts;
83058 (function (ts) {
83059     var ES2015SubstitutionFlags;
83060     (function (ES2015SubstitutionFlags) {
83061         /** Enables substitutions for captured `this` */
83062         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83063         /** Enables substitutions for block-scoped bindings. */
83064         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83065     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83066     var LoopOutParameterFlags;
83067     (function (LoopOutParameterFlags) {
83068         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83069         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83070     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83071     var CopyDirection;
83072     (function (CopyDirection) {
83073         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83074         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83075     })(CopyDirection || (CopyDirection = {}));
83076     var Jump;
83077     (function (Jump) {
83078         Jump[Jump["Break"] = 2] = "Break";
83079         Jump[Jump["Continue"] = 4] = "Continue";
83080         Jump[Jump["Return"] = 8] = "Return";
83081     })(Jump || (Jump = {}));
83082     // Facts we track as we traverse the tree
83083     var HierarchyFacts;
83084     (function (HierarchyFacts) {
83085         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83086         //
83087         // Ancestor facts
83088         //
83089         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83090         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83091         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83092         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83093         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83094         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83095         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83096         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83097         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83098         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83099         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83100         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83101         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83102         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83103         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83104         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83105         //
83106         // Ancestor masks
83107         //
83108         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83109         // We are always in *some* kind of block scope, but only specific block-scope containers are
83110         // top-level or Blocks.
83111         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83112         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83113         // A source file is a top-level block scope.
83114         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83115         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83116         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83117         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83118         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83119         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83120         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83121         // Arrow functions are lexically scoped to their container, but are new block scopes.
83122         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83123         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83124         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83125         // always considered non-static members of a class.
83126         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83127         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83128         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83129         // within an IterationStatement to indicate whether the embedded statement is an
83130         // IterationStatementBlock.
83131         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83132         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83133         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83134         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83135         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83136         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83137         // 'let' declarations.
83138         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83139         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83140         // Blocks (other than function bodies) are new block scopes.
83141         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83142         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83143         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83144         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83145         //
83146         // Subtree facts
83147         //
83148         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83149         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83150         //
83151         // Subtree masks
83152         //
83153         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83154         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83155         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83156     })(HierarchyFacts || (HierarchyFacts = {}));
83157     function transformES2015(context) {
83158         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83159         var compilerOptions = context.getCompilerOptions();
83160         var resolver = context.getEmitResolver();
83161         var previousOnSubstituteNode = context.onSubstituteNode;
83162         var previousOnEmitNode = context.onEmitNode;
83163         context.onEmitNode = onEmitNode;
83164         context.onSubstituteNode = onSubstituteNode;
83165         var currentSourceFile;
83166         var currentText;
83167         var hierarchyFacts;
83168         var taggedTemplateStringDeclarations;
83169         function recordTaggedTemplateString(temp) {
83170             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83171         }
83172         /**
83173          * Used to track if we are emitting body of the converted loop
83174          */
83175         var convertedLoopState;
83176         /**
83177          * Keeps track of whether substitutions have been enabled for specific cases.
83178          * They are persisted between each SourceFile transformation and should not
83179          * be reset.
83180          */
83181         var enabledSubstitutions;
83182         return ts.chainBundle(transformSourceFile);
83183         function transformSourceFile(node) {
83184             if (node.isDeclarationFile) {
83185                 return node;
83186             }
83187             currentSourceFile = node;
83188             currentText = node.text;
83189             var visited = visitSourceFile(node);
83190             ts.addEmitHelpers(visited, context.readEmitHelpers());
83191             currentSourceFile = undefined;
83192             currentText = undefined;
83193             taggedTemplateStringDeclarations = undefined;
83194             hierarchyFacts = 0 /* None */;
83195             return visited;
83196         }
83197         /**
83198          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83199          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83200          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83201          */
83202         function enterSubtree(excludeFacts, includeFacts) {
83203             var ancestorFacts = hierarchyFacts;
83204             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83205             return ancestorFacts;
83206         }
83207         /**
83208          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83209          * subtree, propagating specific facts from the subtree.
83210          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83211          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83212          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83213          */
83214         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83215             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83216         }
83217         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83218             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83219                 && node.kind === 235 /* ReturnStatement */
83220                 && !node.expression;
83221         }
83222         function shouldVisitNode(node) {
83223             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83224                 || convertedLoopState !== undefined
83225                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83226                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83227                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83228         }
83229         function visitor(node) {
83230             if (shouldVisitNode(node)) {
83231                 return visitJavaScript(node);
83232             }
83233             else {
83234                 return node;
83235             }
83236         }
83237         function callExpressionVisitor(node) {
83238             if (node.kind === 102 /* SuperKeyword */) {
83239                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83240             }
83241             return visitor(node);
83242         }
83243         function visitJavaScript(node) {
83244             switch (node.kind) {
83245                 case 120 /* StaticKeyword */:
83246                     return undefined; // elide static keyword
83247                 case 245 /* ClassDeclaration */:
83248                     return visitClassDeclaration(node);
83249                 case 214 /* ClassExpression */:
83250                     return visitClassExpression(node);
83251                 case 156 /* Parameter */:
83252                     return visitParameter(node);
83253                 case 244 /* FunctionDeclaration */:
83254                     return visitFunctionDeclaration(node);
83255                 case 202 /* ArrowFunction */:
83256                     return visitArrowFunction(node);
83257                 case 201 /* FunctionExpression */:
83258                     return visitFunctionExpression(node);
83259                 case 242 /* VariableDeclaration */:
83260                     return visitVariableDeclaration(node);
83261                 case 75 /* Identifier */:
83262                     return visitIdentifier(node);
83263                 case 243 /* VariableDeclarationList */:
83264                     return visitVariableDeclarationList(node);
83265                 case 237 /* SwitchStatement */:
83266                     return visitSwitchStatement(node);
83267                 case 251 /* CaseBlock */:
83268                     return visitCaseBlock(node);
83269                 case 223 /* Block */:
83270                     return visitBlock(node, /*isFunctionBody*/ false);
83271                 case 234 /* BreakStatement */:
83272                 case 233 /* ContinueStatement */:
83273                     return visitBreakOrContinueStatement(node);
83274                 case 238 /* LabeledStatement */:
83275                     return visitLabeledStatement(node);
83276                 case 228 /* DoStatement */:
83277                 case 229 /* WhileStatement */:
83278                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83279                 case 230 /* ForStatement */:
83280                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83281                 case 231 /* ForInStatement */:
83282                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83283                 case 232 /* ForOfStatement */:
83284                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83285                 case 226 /* ExpressionStatement */:
83286                     return visitExpressionStatement(node);
83287                 case 193 /* ObjectLiteralExpression */:
83288                     return visitObjectLiteralExpression(node);
83289                 case 280 /* CatchClause */:
83290                     return visitCatchClause(node);
83291                 case 282 /* ShorthandPropertyAssignment */:
83292                     return visitShorthandPropertyAssignment(node);
83293                 case 154 /* ComputedPropertyName */:
83294                     return visitComputedPropertyName(node);
83295                 case 192 /* ArrayLiteralExpression */:
83296                     return visitArrayLiteralExpression(node);
83297                 case 196 /* CallExpression */:
83298                     return visitCallExpression(node);
83299                 case 197 /* NewExpression */:
83300                     return visitNewExpression(node);
83301                 case 200 /* ParenthesizedExpression */:
83302                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83303                 case 209 /* BinaryExpression */:
83304                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83305                 case 14 /* NoSubstitutionTemplateLiteral */:
83306                 case 15 /* TemplateHead */:
83307                 case 16 /* TemplateMiddle */:
83308                 case 17 /* TemplateTail */:
83309                     return visitTemplateLiteral(node);
83310                 case 10 /* StringLiteral */:
83311                     return visitStringLiteral(node);
83312                 case 8 /* NumericLiteral */:
83313                     return visitNumericLiteral(node);
83314                 case 198 /* TaggedTemplateExpression */:
83315                     return visitTaggedTemplateExpression(node);
83316                 case 211 /* TemplateExpression */:
83317                     return visitTemplateExpression(node);
83318                 case 212 /* YieldExpression */:
83319                     return visitYieldExpression(node);
83320                 case 213 /* SpreadElement */:
83321                     return visitSpreadElement(node);
83322                 case 102 /* SuperKeyword */:
83323                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83324                 case 104 /* ThisKeyword */:
83325                     return visitThisKeyword(node);
83326                 case 219 /* MetaProperty */:
83327                     return visitMetaProperty(node);
83328                 case 161 /* MethodDeclaration */:
83329                     return visitMethodDeclaration(node);
83330                 case 163 /* GetAccessor */:
83331                 case 164 /* SetAccessor */:
83332                     return visitAccessorDeclaration(node);
83333                 case 225 /* VariableStatement */:
83334                     return visitVariableStatement(node);
83335                 case 235 /* ReturnStatement */:
83336                     return visitReturnStatement(node);
83337                 default:
83338                     return ts.visitEachChild(node, visitor, context);
83339             }
83340         }
83341         function visitSourceFile(node) {
83342             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83343             var prologue = [];
83344             var statements = [];
83345             startLexicalEnvironment();
83346             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83347             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83348             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83349             if (taggedTemplateStringDeclarations) {
83350                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83351             }
83352             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83353             insertCaptureThisForNodeIfNeeded(prologue, node);
83354             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83355             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83356         }
83357         function visitSwitchStatement(node) {
83358             if (convertedLoopState !== undefined) {
83359                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83360                 // for switch statement allow only non-labeled break
83361                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83362                 var result = ts.visitEachChild(node, visitor, context);
83363                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83364                 return result;
83365             }
83366             return ts.visitEachChild(node, visitor, context);
83367         }
83368         function visitCaseBlock(node) {
83369             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83370             var updated = ts.visitEachChild(node, visitor, context);
83371             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83372             return updated;
83373         }
83374         function returnCapturedThis(node) {
83375             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83376         }
83377         function visitReturnStatement(node) {
83378             if (convertedLoopState) {
83379                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83380                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83381                     node = returnCapturedThis(node);
83382                 }
83383                 return ts.createReturn(ts.createObjectLiteral([
83384                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83385                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83386                         : ts.createVoidZero())
83387                 ]));
83388             }
83389             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83390                 return returnCapturedThis(node);
83391             }
83392             return ts.visitEachChild(node, visitor, context);
83393         }
83394         function visitThisKeyword(node) {
83395             if (hierarchyFacts & 2 /* ArrowFunction */) {
83396                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83397             }
83398             if (convertedLoopState) {
83399                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83400                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83401                     convertedLoopState.containsLexicalThis = true;
83402                     return node;
83403                 }
83404                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83405             }
83406             return node;
83407         }
83408         function visitIdentifier(node) {
83409             if (!convertedLoopState) {
83410                 return node;
83411             }
83412             if (ts.isGeneratedIdentifier(node)) {
83413                 return node;
83414             }
83415             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83416                 return node;
83417             }
83418             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83419         }
83420         function visitBreakOrContinueStatement(node) {
83421             if (convertedLoopState) {
83422                 // check if we can emit break/continue as is
83423                 // it is possible if either
83424                 //   - break/continue is labeled and label is located inside the converted loop
83425                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83426                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83427                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83428                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83429                 if (!canUseBreakOrContinue) {
83430                     var labelMarker = void 0;
83431                     var label = node.label;
83432                     if (!label) {
83433                         if (node.kind === 234 /* BreakStatement */) {
83434                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83435                             labelMarker = "break";
83436                         }
83437                         else {
83438                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83439                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83440                             labelMarker = "continue";
83441                         }
83442                     }
83443                     else {
83444                         if (node.kind === 234 /* BreakStatement */) {
83445                             labelMarker = "break-" + label.escapedText;
83446                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83447                         }
83448                         else {
83449                             labelMarker = "continue-" + label.escapedText;
83450                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83451                         }
83452                     }
83453                     var returnExpression = ts.createLiteral(labelMarker);
83454                     if (convertedLoopState.loopOutParameters.length) {
83455                         var outParams = convertedLoopState.loopOutParameters;
83456                         var expr = void 0;
83457                         for (var i = 0; i < outParams.length; i++) {
83458                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83459                             if (i === 0) {
83460                                 expr = copyExpr;
83461                             }
83462                             else {
83463                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83464                             }
83465                         }
83466                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83467                     }
83468                     return ts.createReturn(returnExpression);
83469                 }
83470             }
83471             return ts.visitEachChild(node, visitor, context);
83472         }
83473         /**
83474          * Visits a ClassDeclaration and transforms it into a variable statement.
83475          *
83476          * @param node A ClassDeclaration node.
83477          */
83478         function visitClassDeclaration(node) {
83479             // [source]
83480             //      class C { }
83481             //
83482             // [output]
83483             //      var C = (function () {
83484             //          function C() {
83485             //          }
83486             //          return C;
83487             //      }());
83488             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83489             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83490             ts.setOriginalNode(variable, node);
83491             var statements = [];
83492             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83493             ts.setOriginalNode(statement, node);
83494             ts.setTextRange(statement, node);
83495             ts.startOnNewLine(statement);
83496             statements.push(statement);
83497             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83498             if (ts.hasModifier(node, 1 /* Export */)) {
83499                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83500                     ? ts.createExportDefault(ts.getLocalName(node))
83501                     : ts.createExternalModuleExport(ts.getLocalName(node));
83502                 ts.setOriginalNode(exportStatement, statement);
83503                 statements.push(exportStatement);
83504             }
83505             var emitFlags = ts.getEmitFlags(node);
83506             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83507                 // Add a DeclarationMarker as a marker for the end of the declaration
83508                 statements.push(ts.createEndOfDeclarationMarker(node));
83509                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83510             }
83511             return ts.singleOrMany(statements);
83512         }
83513         /**
83514          * Visits a ClassExpression and transforms it into an expression.
83515          *
83516          * @param node A ClassExpression node.
83517          */
83518         function visitClassExpression(node) {
83519             // [source]
83520             //      C = class { }
83521             //
83522             // [output]
83523             //      C = (function () {
83524             //          function class_1() {
83525             //          }
83526             //          return class_1;
83527             //      }())
83528             return transformClassLikeDeclarationToExpression(node);
83529         }
83530         /**
83531          * Transforms a ClassExpression or ClassDeclaration into an expression.
83532          *
83533          * @param node A ClassExpression or ClassDeclaration node.
83534          */
83535         function transformClassLikeDeclarationToExpression(node) {
83536             // [source]
83537             //      class C extends D {
83538             //          constructor() {}
83539             //          method() {}
83540             //          get prop() {}
83541             //          set prop(v) {}
83542             //      }
83543             //
83544             // [output]
83545             //      (function (_super) {
83546             //          __extends(C, _super);
83547             //          function C() {
83548             //          }
83549             //          C.prototype.method = function () {}
83550             //          Object.defineProperty(C.prototype, "prop", {
83551             //              get: function() {},
83552             //              set: function() {},
83553             //              enumerable: true,
83554             //              configurable: true
83555             //          });
83556             //          return C;
83557             //      }(D))
83558             if (node.name) {
83559                 enableSubstitutionsForBlockScopedBindings();
83560             }
83561             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83562             var classFunction = ts.createFunctionExpression(
83563             /*modifiers*/ undefined, 
83564             /*asteriskToken*/ undefined, 
83565             /*name*/ undefined, 
83566             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83567             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83568             // To preserve the behavior of the old emitter, we explicitly indent
83569             // the body of the function here if it was requested in an earlier
83570             // transformation.
83571             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83572             // "inner" and "outer" below are added purely to preserve source map locations from
83573             // the old emitter
83574             var inner = ts.createPartiallyEmittedExpression(classFunction);
83575             inner.end = node.end;
83576             ts.setEmitFlags(inner, 1536 /* NoComments */);
83577             var outer = ts.createPartiallyEmittedExpression(inner);
83578             outer.end = ts.skipTrivia(currentText, node.pos);
83579             ts.setEmitFlags(outer, 1536 /* NoComments */);
83580             var result = ts.createParen(ts.createCall(outer, 
83581             /*typeArguments*/ undefined, extendsClauseElement
83582                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83583                 : []));
83584             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83585             return result;
83586         }
83587         /**
83588          * Transforms a ClassExpression or ClassDeclaration into a function body.
83589          *
83590          * @param node A ClassExpression or ClassDeclaration node.
83591          * @param extendsClauseElement The expression for the class `extends` clause.
83592          */
83593         function transformClassBody(node, extendsClauseElement) {
83594             var statements = [];
83595             startLexicalEnvironment();
83596             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83597             addConstructor(statements, node, extendsClauseElement);
83598             addClassMembers(statements, node);
83599             // Create a synthetic text range for the return statement.
83600             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83601             var localName = ts.getInternalName(node);
83602             // The following partially-emitted expression exists purely to align our sourcemap
83603             // emit with the original emitter.
83604             var outer = ts.createPartiallyEmittedExpression(localName);
83605             outer.end = closingBraceLocation.end;
83606             ts.setEmitFlags(outer, 1536 /* NoComments */);
83607             var statement = ts.createReturn(outer);
83608             statement.pos = closingBraceLocation.pos;
83609             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83610             statements.push(statement);
83611             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83612             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83613             ts.setEmitFlags(block, 1536 /* NoComments */);
83614             return block;
83615         }
83616         /**
83617          * Adds a call to the `__extends` helper if needed for a class.
83618          *
83619          * @param statements The statements of the class body function.
83620          * @param node The ClassExpression or ClassDeclaration node.
83621          * @param extendsClauseElement The expression for the class `extends` clause.
83622          */
83623         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83624             if (extendsClauseElement) {
83625                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83626                 /*location*/ extendsClauseElement));
83627             }
83628         }
83629         /**
83630          * Adds the constructor of the class to a class body function.
83631          *
83632          * @param statements The statements of the class body function.
83633          * @param node The ClassExpression or ClassDeclaration node.
83634          * @param extendsClauseElement The expression for the class `extends` clause.
83635          */
83636         function addConstructor(statements, node, extendsClauseElement) {
83637             var savedConvertedLoopState = convertedLoopState;
83638             convertedLoopState = undefined;
83639             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83640             var constructor = ts.getFirstConstructorWithBody(node);
83641             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83642             var constructorFunction = ts.createFunctionDeclaration(
83643             /*decorators*/ undefined, 
83644             /*modifiers*/ undefined, 
83645             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83646             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83647             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83648             ts.setTextRange(constructorFunction, constructor || node);
83649             if (extendsClauseElement) {
83650                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83651             }
83652             statements.push(constructorFunction);
83653             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83654             convertedLoopState = savedConvertedLoopState;
83655         }
83656         /**
83657          * Transforms the parameters of the constructor declaration of a class.
83658          *
83659          * @param constructor The constructor for the class.
83660          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83661          *                            synthesized `super` call.
83662          */
83663         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83664             // If the TypeScript transformer needed to synthesize a constructor for property
83665             // initializers, it would have also added a synthetic `...args` parameter and
83666             // `super` call.
83667             // If this is the case, we do not include the synthetic `...args` parameter and
83668             // will instead use the `arguments` object in ES5/3.
83669             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83670                 || [];
83671         }
83672         function createDefaultConstructorBody(node, isDerivedClass) {
83673             // We must be here because the user didn't write a constructor
83674             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83675             // If that's the case we can just immediately return the result of a 'super()' call.
83676             var statements = [];
83677             resumeLexicalEnvironment();
83678             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83679             if (isDerivedClass) {
83680                 // return _super !== null && _super.apply(this, arguments) || this;
83681                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83682             }
83683             var statementsArray = ts.createNodeArray(statements);
83684             ts.setTextRange(statementsArray, node.members);
83685             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83686             ts.setTextRange(block, node);
83687             ts.setEmitFlags(block, 1536 /* NoComments */);
83688             return block;
83689         }
83690         /**
83691          * Transforms the body of a constructor declaration of a class.
83692          *
83693          * @param constructor The constructor for the class.
83694          * @param node The node which contains the constructor.
83695          * @param extendsClauseElement The expression for the class `extends` clause.
83696          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83697          *                            synthesized `super` call.
83698          */
83699         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83700             // determine whether the class is known syntactically to be a derived class (e.g. a
83701             // class that extends a value that is not syntactically known to be `null`).
83702             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83703             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83704             // representation:
83705             //
83706             // ```
83707             // // es2015 (source)
83708             // class C extends Base { }
83709             //
83710             // // es5 (transformed)
83711             // var C = (function (_super) {
83712             //     function C() {
83713             //         return _super.apply(this, arguments) || this;
83714             //     }
83715             //     return C;
83716             // })(Base);
83717             // ```
83718             if (!constructor)
83719                 return createDefaultConstructorBody(node, isDerivedClass);
83720             // The prologue will contain all leading standard and custom prologue statements added by this transform
83721             var prologue = [];
83722             var statements = [];
83723             resumeLexicalEnvironment();
83724             // If a super call has already been synthesized,
83725             // we're going to assume that we should just transform everything after that.
83726             // The assumption is that no prior step in the pipeline has added any prologue directives.
83727             var statementOffset = 0;
83728             if (!hasSynthesizedSuper)
83729                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83730             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83731             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83732             if (!hasSynthesizedSuper)
83733                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83734             // If the first statement is a call to `super()`, visit the statement directly
83735             var superCallExpression;
83736             if (hasSynthesizedSuper) {
83737                 superCallExpression = createDefaultSuperCallOrThis();
83738             }
83739             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83740                 var firstStatement = constructor.body.statements[statementOffset];
83741                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83742                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83743                 }
83744             }
83745             if (superCallExpression) {
83746                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83747                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83748             }
83749             // visit the remaining statements
83750             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83751             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83752             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83753             if (isDerivedClass) {
83754                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83755                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83756                     // following representation:
83757                     //
83758                     // ```
83759                     // // es2015 (source)
83760                     // class C extends Base {
83761                     //     constructor() {
83762                     //         super("foo");
83763                     //     }
83764                     // }
83765                     //
83766                     // // es5 (transformed)
83767                     // var C = (function (_super) {
83768                     //     function C() {
83769                     //         return _super.call(this, "foo") || this;
83770                     //     }
83771                     //     return C;
83772                     // })(Base);
83773                     // ```
83774                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83775                     var returnStatement = ts.createReturn(superCallExpression);
83776                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83777                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83778                     statements.push(returnStatement);
83779                 }
83780                 else {
83781                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83782                     //
83783                     // ```
83784                     // // es2015 (source)
83785                     // class C extends Base {
83786                     //     constructor() {
83787                     //         super("foo");
83788                     //         this.x = 1;
83789                     //     }
83790                     // }
83791                     //
83792                     // // es5 (transformed)
83793                     // var C = (function (_super) {
83794                     //     function C() {
83795                     //         var _this = _super.call(this, "foo") || this;
83796                     //         _this.x = 1;
83797                     //         return _this;
83798                     //     }
83799                     //     return C;
83800                     // })(Base);
83801                     // ```
83802                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83803                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83804                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83805                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83806                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83807                     }
83808                 }
83809             }
83810             else {
83811                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83812                 // captured when necessitated by an arrow function capturing the lexical `this`:
83813                 //
83814                 // ```
83815                 // // es2015
83816                 // class C {}
83817                 //
83818                 // // es5
83819                 // var C = (function () {
83820                 //     function C() {
83821                 //     }
83822                 //     return C;
83823                 // })();
83824                 // ```
83825                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
83826             }
83827             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
83828             /*location*/ constructor.body.statements), 
83829             /*multiLine*/ true);
83830             ts.setTextRange(block, constructor.body);
83831             return block;
83832         }
83833         /**
83834          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
83835          * It would generate obviously dead code, so we'll try to make things a little bit prettier
83836          * by doing a minimal check on whether some common patterns always explicitly return.
83837          */
83838         function isSufficientlyCoveredByReturnStatements(statement) {
83839             // A return statement is considered covered.
83840             if (statement.kind === 235 /* ReturnStatement */) {
83841                 return true;
83842             }
83843             // An if-statement with two covered branches is covered.
83844             else if (statement.kind === 227 /* IfStatement */) {
83845                 var ifStatement = statement;
83846                 if (ifStatement.elseStatement) {
83847                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
83848                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
83849                 }
83850             }
83851             // A block is covered if it has a last statement which is covered.
83852             else if (statement.kind === 223 /* Block */) {
83853                 var lastStatement = ts.lastOrUndefined(statement.statements);
83854                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
83855                     return true;
83856                 }
83857             }
83858             return false;
83859         }
83860         function createActualThis() {
83861             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
83862         }
83863         function createDefaultSuperCallOrThis() {
83864             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
83865         }
83866         /**
83867          * Visits a parameter declaration.
83868          *
83869          * @param node A ParameterDeclaration node.
83870          */
83871         function visitParameter(node) {
83872             if (node.dotDotDotToken) {
83873                 // rest parameters are elided
83874                 return undefined;
83875             }
83876             else if (ts.isBindingPattern(node.name)) {
83877                 // Binding patterns are converted into a generated name and are
83878                 // evaluated inside the function body.
83879                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83880                 /*decorators*/ undefined, 
83881                 /*modifiers*/ undefined, 
83882                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
83883                 /*questionToken*/ undefined, 
83884                 /*type*/ undefined, 
83885                 /*initializer*/ undefined), 
83886                 /*location*/ node), 
83887                 /*original*/ node);
83888             }
83889             else if (node.initializer) {
83890                 // Initializers are elided
83891                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83892                 /*decorators*/ undefined, 
83893                 /*modifiers*/ undefined, 
83894                 /*dotDotDotToken*/ undefined, node.name, 
83895                 /*questionToken*/ undefined, 
83896                 /*type*/ undefined, 
83897                 /*initializer*/ undefined), 
83898                 /*location*/ node), 
83899                 /*original*/ node);
83900             }
83901             else {
83902                 return node;
83903             }
83904         }
83905         function hasDefaultValueOrBindingPattern(node) {
83906             return node.initializer !== undefined
83907                 || ts.isBindingPattern(node.name);
83908         }
83909         /**
83910          * Adds statements to the body of a function-like node if it contains parameters with
83911          * binding patterns or initializers.
83912          *
83913          * @param statements The statements for the new function body.
83914          * @param node A function-like node.
83915          */
83916         function addDefaultValueAssignmentsIfNeeded(statements, node) {
83917             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
83918                 return false;
83919             }
83920             var added = false;
83921             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83922                 var parameter = _a[_i];
83923                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
83924                 // A rest parameter cannot have a binding pattern or an initializer,
83925                 // so let's just ignore it.
83926                 if (dotDotDotToken) {
83927                     continue;
83928                 }
83929                 if (ts.isBindingPattern(name)) {
83930                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
83931                 }
83932                 else if (initializer) {
83933                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
83934                     added = true;
83935                 }
83936             }
83937             return added;
83938         }
83939         /**
83940          * Adds statements to the body of a function-like node for parameters with binding patterns
83941          *
83942          * @param statements The statements for the new function body.
83943          * @param parameter The parameter for the function.
83944          * @param name The name of the parameter.
83945          * @param initializer The initializer for the parameter.
83946          */
83947         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
83948             // In cases where a binding pattern is simply '[]' or '{}',
83949             // we usually don't want to emit a var declaration; however, in the presence
83950             // of an initializer, we must emit that expression to preserve side effects.
83951             if (name.elements.length > 0) {
83952                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
83953                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
83954                 return true;
83955             }
83956             else if (initializer) {
83957                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
83958                 return true;
83959             }
83960             return false;
83961         }
83962         /**
83963          * Adds statements to the body of a function-like node for parameters with initializers.
83964          *
83965          * @param statements The statements for the new function body.
83966          * @param parameter The parameter for the function.
83967          * @param name The name of the parameter.
83968          * @param initializer The initializer for the parameter.
83969          */
83970         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
83971             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
83972             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
83973                 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 */))
83974             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
83975             ts.startOnNewLine(statement);
83976             ts.setTextRange(statement, parameter);
83977             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
83978             ts.insertStatementAfterCustomPrologue(statements, statement);
83979         }
83980         /**
83981          * Gets a value indicating whether we need to add statements to handle a rest parameter.
83982          *
83983          * @param node A ParameterDeclaration node.
83984          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
83985          *                                          part of a constructor declaration with a
83986          *                                          synthesized call to `super`
83987          */
83988         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
83989             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
83990         }
83991         /**
83992          * Adds statements to the body of a function-like node if it contains a rest parameter.
83993          *
83994          * @param statements The statements for the new function body.
83995          * @param node A function-like node.
83996          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
83997          *                                          part of a constructor declaration with a
83998          *                                          synthesized call to `super`
83999          */
84000         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84001             var prologueStatements = [];
84002             var parameter = ts.lastOrUndefined(node.parameters);
84003             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84004                 return false;
84005             }
84006             // `declarationName` is the name of the local declaration for the parameter.
84007             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84008             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84009             // `expressionName` is the name of the parameter used in expressions.
84010             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84011             var restIndex = node.parameters.length - 1;
84012             var temp = ts.createLoopVariable();
84013             // var param = [];
84014             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84015             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84016                 ts.createVariableDeclaration(declarationName, 
84017                 /*type*/ undefined, ts.createArrayLiteral([]))
84018             ])), 
84019             /*location*/ parameter), 1048576 /* CustomPrologue */));
84020             // for (var _i = restIndex; _i < arguments.length; _i++) {
84021             //   param[_i - restIndex] = arguments[_i];
84022             // }
84023             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84024                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84025             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84026                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84027                     ? temp
84028                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84029                 /*location*/ parameter))
84030             ]));
84031             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84032             ts.startOnNewLine(forStatement);
84033             prologueStatements.push(forStatement);
84034             if (parameter.name.kind !== 75 /* Identifier */) {
84035                 // do the actual destructuring of the rest parameter if necessary
84036                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84037                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84038             }
84039             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84040             return true;
84041         }
84042         /**
84043          * Adds a statement to capture the `this` of a function declaration if it is needed.
84044          * NOTE: This must be executed *after* the subtree has been visited.
84045          *
84046          * @param statements The statements for the new function body.
84047          * @param node A node.
84048          */
84049         function insertCaptureThisForNodeIfNeeded(statements, node) {
84050             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84051                 insertCaptureThisForNode(statements, node, ts.createThis());
84052                 return true;
84053             }
84054             return false;
84055         }
84056         function insertCaptureThisForNode(statements, node, initializer) {
84057             enableSubstitutionsForCapturedThis();
84058             var captureThisStatement = ts.createVariableStatement(
84059             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84060                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84061                 /*type*/ undefined, initializer)
84062             ]));
84063             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84064             ts.setSourceMapRange(captureThisStatement, node);
84065             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84066         }
84067         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84068             if (hierarchyFacts & 16384 /* NewTarget */) {
84069                 var newTarget = void 0;
84070                 switch (node.kind) {
84071                     case 202 /* ArrowFunction */:
84072                         return statements;
84073                     case 161 /* MethodDeclaration */:
84074                     case 163 /* GetAccessor */:
84075                     case 164 /* SetAccessor */:
84076                         // Methods and accessors cannot be constructors, so 'new.target' will
84077                         // always return 'undefined'.
84078                         newTarget = ts.createVoidZero();
84079                         break;
84080                     case 162 /* Constructor */:
84081                         // Class constructors can only be called with `new`, so `this.constructor`
84082                         // should be relatively safe to use.
84083                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84084                         break;
84085                     case 244 /* FunctionDeclaration */:
84086                     case 201 /* FunctionExpression */:
84087                         // Functions can be called or constructed, and may have a `this` due to
84088                         // being a member or when calling an imported function via `other_1.f()`.
84089                         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());
84090                         break;
84091                     default:
84092                         return ts.Debug.failBadSyntaxKind(node);
84093                 }
84094                 var captureNewTargetStatement = ts.createVariableStatement(
84095                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84096                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84097                     /*type*/ undefined, newTarget)
84098                 ]));
84099                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84100                 if (copyOnWrite) {
84101                     statements = statements.slice();
84102                 }
84103                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84104             }
84105             return statements;
84106         }
84107         /**
84108          * Adds statements to the class body function for a class to define the members of the
84109          * class.
84110          *
84111          * @param statements The statements for the class body function.
84112          * @param node The ClassExpression or ClassDeclaration node.
84113          */
84114         function addClassMembers(statements, node) {
84115             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84116                 var member = _a[_i];
84117                 switch (member.kind) {
84118                     case 222 /* SemicolonClassElement */:
84119                         statements.push(transformSemicolonClassElementToStatement(member));
84120                         break;
84121                     case 161 /* MethodDeclaration */:
84122                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84123                         break;
84124                     case 163 /* GetAccessor */:
84125                     case 164 /* SetAccessor */:
84126                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84127                         if (member === accessors.firstAccessor) {
84128                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84129                         }
84130                         break;
84131                     case 162 /* Constructor */:
84132                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84133                         break;
84134                     default:
84135                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84136                         break;
84137                 }
84138             }
84139         }
84140         /**
84141          * Transforms a SemicolonClassElement into a statement for a class body function.
84142          *
84143          * @param member The SemicolonClassElement node.
84144          */
84145         function transformSemicolonClassElementToStatement(member) {
84146             return ts.setTextRange(ts.createEmptyStatement(), member);
84147         }
84148         /**
84149          * Transforms a MethodDeclaration into a statement for a class body function.
84150          *
84151          * @param receiver The receiver for the member.
84152          * @param member The MethodDeclaration node.
84153          */
84154         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84155             var commentRange = ts.getCommentRange(member);
84156             var sourceMapRange = ts.getSourceMapRange(member);
84157             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84158             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84159             var e;
84160             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84161                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84162                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84163                         : propertyName;
84164                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84165             }
84166             else {
84167                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84168                 e = ts.createAssignment(memberName, memberFunction);
84169             }
84170             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84171             ts.setSourceMapRange(memberFunction, sourceMapRange);
84172             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84173             ts.setOriginalNode(statement, member);
84174             ts.setCommentRange(statement, commentRange);
84175             // The location for the statement is used to emit comments only.
84176             // No source map should be emitted for this statement to align with the
84177             // old emitter.
84178             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84179             return statement;
84180         }
84181         /**
84182          * Transforms a set of related of get/set accessors into a statement for a class body function.
84183          *
84184          * @param receiver The receiver for the member.
84185          * @param accessors The set of related get/set accessors.
84186          */
84187         function transformAccessorsToStatement(receiver, accessors, container) {
84188             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84189             // The location for the statement is used to emit source maps only.
84190             // No comments should be emitted for this statement to align with the
84191             // old emitter.
84192             ts.setEmitFlags(statement, 1536 /* NoComments */);
84193             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84194             return statement;
84195         }
84196         /**
84197          * Transforms a set of related get/set accessors into an expression for either a class
84198          * body function or an ObjectLiteralExpression with computed properties.
84199          *
84200          * @param receiver The receiver for the member.
84201          */
84202         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84203             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84204             // To align with source maps in the old emitter, the receiver and property name
84205             // arguments are both mapped contiguously to the accessor name.
84206             var target = ts.getMutableClone(receiver);
84207             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84208             ts.setSourceMapRange(target, firstAccessor.name);
84209             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84210             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84211                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84212             }
84213             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84214             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84215             ts.setSourceMapRange(propertyName, firstAccessor.name);
84216             var properties = [];
84217             if (getAccessor) {
84218                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84219                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84220                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84221                 var getter = ts.createPropertyAssignment("get", getterFunction);
84222                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84223                 properties.push(getter);
84224             }
84225             if (setAccessor) {
84226                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84227                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84228                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84229                 var setter = ts.createPropertyAssignment("set", setterFunction);
84230                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84231                 properties.push(setter);
84232             }
84233             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84234             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84235             /*typeArguments*/ undefined, [
84236                 target,
84237                 propertyName,
84238                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84239             ]);
84240             if (startsOnNewLine) {
84241                 ts.startOnNewLine(call);
84242             }
84243             return call;
84244         }
84245         /**
84246          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84247          *
84248          * @param node An ArrowFunction node.
84249          */
84250         function visitArrowFunction(node) {
84251             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84252                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84253             }
84254             var savedConvertedLoopState = convertedLoopState;
84255             convertedLoopState = undefined;
84256             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84257             var func = ts.createFunctionExpression(
84258             /*modifiers*/ undefined, 
84259             /*asteriskToken*/ undefined, 
84260             /*name*/ undefined, 
84261             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84262             /*type*/ undefined, transformFunctionBody(node));
84263             ts.setTextRange(func, node);
84264             ts.setOriginalNode(func, node);
84265             ts.setEmitFlags(func, 8 /* CapturesThis */);
84266             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84267                 enableSubstitutionsForCapturedThis();
84268             }
84269             // If an arrow function contains
84270             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84271             convertedLoopState = savedConvertedLoopState;
84272             return func;
84273         }
84274         /**
84275          * Visits a FunctionExpression node.
84276          *
84277          * @param node a FunctionExpression node.
84278          */
84279         function visitFunctionExpression(node) {
84280             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84281                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84282                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84283             var savedConvertedLoopState = convertedLoopState;
84284             convertedLoopState = undefined;
84285             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84286             var body = transformFunctionBody(node);
84287             var name = hierarchyFacts & 16384 /* NewTarget */
84288                 ? ts.getLocalName(node)
84289                 : node.name;
84290             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84291             convertedLoopState = savedConvertedLoopState;
84292             return ts.updateFunctionExpression(node, 
84293             /*modifiers*/ undefined, node.asteriskToken, name, 
84294             /*typeParameters*/ undefined, parameters, 
84295             /*type*/ undefined, body);
84296         }
84297         /**
84298          * Visits a FunctionDeclaration node.
84299          *
84300          * @param node a FunctionDeclaration node.
84301          */
84302         function visitFunctionDeclaration(node) {
84303             var savedConvertedLoopState = convertedLoopState;
84304             convertedLoopState = undefined;
84305             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
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.updateFunctionDeclaration(node, 
84314             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84315             /*typeParameters*/ undefined, parameters, 
84316             /*type*/ undefined, body);
84317         }
84318         /**
84319          * Transforms a function-like node into a FunctionExpression.
84320          *
84321          * @param node The function-like node to transform.
84322          * @param location The source-map location for the new FunctionExpression.
84323          * @param name The name of the new FunctionExpression.
84324          */
84325         function transformFunctionLikeToExpression(node, location, name, container) {
84326             var savedConvertedLoopState = convertedLoopState;
84327             convertedLoopState = undefined;
84328             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84329                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84330                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84331             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84332             var body = transformFunctionBody(node);
84333             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84334                 name = ts.getGeneratedNameForNode(node);
84335             }
84336             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84337             convertedLoopState = savedConvertedLoopState;
84338             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84339             /*modifiers*/ undefined, node.asteriskToken, name, 
84340             /*typeParameters*/ undefined, parameters, 
84341             /*type*/ undefined, body), location), 
84342             /*original*/ node);
84343         }
84344         /**
84345          * Transforms the body of a function-like node.
84346          *
84347          * @param node A function-like node.
84348          */
84349         function transformFunctionBody(node) {
84350             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84351             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84352             var statementsLocation;
84353             var closeBraceLocation;
84354             var prologue = [];
84355             var statements = [];
84356             var body = node.body;
84357             var statementOffset;
84358             resumeLexicalEnvironment();
84359             if (ts.isBlock(body)) {
84360                 // ensureUseStrict is false because no new prologue-directive should be added.
84361                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84362                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84363                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84364                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84365             }
84366             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84367             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84368             if (ts.isBlock(body)) {
84369                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84370                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84371                 statementsLocation = body.statements;
84372                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84373                 // If the original body was a multi-line block, this must be a multi-line block.
84374                 if (!multiLine && body.multiLine) {
84375                     multiLine = true;
84376                 }
84377             }
84378             else {
84379                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84380                 // To align with the old emitter, we use a synthetic end position on the location
84381                 // for the statement list we synthesize when we down-level an arrow function with
84382                 // an expression function body. This prevents both comments and source maps from
84383                 // being emitted for the end position only.
84384                 statementsLocation = ts.moveRangeEnd(body, -1);
84385                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84386                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84387                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84388                         singleLine = true;
84389                     }
84390                     else {
84391                         multiLine = true;
84392                     }
84393                 }
84394                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84395                 var returnStatement = ts.createReturn(expression);
84396                 ts.setTextRange(returnStatement, body);
84397                 ts.moveSyntheticComments(returnStatement, body);
84398                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84399                 statements.push(returnStatement);
84400                 // To align with the source map emit for the old emitter, we set a custom
84401                 // source map location for the close brace.
84402                 closeBraceLocation = body;
84403             }
84404             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84405             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84406             insertCaptureThisForNodeIfNeeded(prologue, node);
84407             // If we added any final generated statements, this must be a multi-line block
84408             if (ts.some(prologue)) {
84409                 multiLine = true;
84410             }
84411             statements.unshift.apply(statements, prologue);
84412             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84413                 // no changes were made, preserve the tree
84414                 return body;
84415             }
84416             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84417             ts.setTextRange(block, node.body);
84418             if (!multiLine && singleLine) {
84419                 ts.setEmitFlags(block, 1 /* SingleLine */);
84420             }
84421             if (closeBraceLocation) {
84422                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84423             }
84424             ts.setOriginalNode(block, node.body);
84425             return block;
84426         }
84427         function visitBlock(node, isFunctionBody) {
84428             if (isFunctionBody) {
84429                 // A function body is not a block scope.
84430                 return ts.visitEachChild(node, visitor, context);
84431             }
84432             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84433                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84434                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84435             var updated = ts.visitEachChild(node, visitor, context);
84436             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84437             return updated;
84438         }
84439         /**
84440          * Visits an ExpressionStatement that contains a destructuring assignment.
84441          *
84442          * @param node An ExpressionStatement node.
84443          */
84444         function visitExpressionStatement(node) {
84445             // If we are here it is most likely because our expression is a destructuring assignment.
84446             switch (node.expression.kind) {
84447                 case 200 /* ParenthesizedExpression */:
84448                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84449                 case 209 /* BinaryExpression */:
84450                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84451             }
84452             return ts.visitEachChild(node, visitor, context);
84453         }
84454         /**
84455          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84456          *
84457          * @param node A ParenthesizedExpression node.
84458          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84459          *                                of a destructuring assignment.
84460          */
84461         function visitParenthesizedExpression(node, needsDestructuringValue) {
84462             // If we are here it is most likely because our expression is a destructuring assignment.
84463             if (!needsDestructuringValue) {
84464                 // By default we always emit the RHS at the end of a flattened destructuring
84465                 // expression. If we are in a state where we do not need the destructuring value,
84466                 // we pass that information along to the children that care about it.
84467                 switch (node.expression.kind) {
84468                     case 200 /* ParenthesizedExpression */:
84469                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84470                     case 209 /* BinaryExpression */:
84471                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84472                 }
84473             }
84474             return ts.visitEachChild(node, visitor, context);
84475         }
84476         /**
84477          * Visits a BinaryExpression that contains a destructuring assignment.
84478          *
84479          * @param node A BinaryExpression node.
84480          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84481          *                                of a destructuring assignment.
84482          */
84483         function visitBinaryExpression(node, needsDestructuringValue) {
84484             // If we are here it is because this is a destructuring assignment.
84485             if (ts.isDestructuringAssignment(node)) {
84486                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84487             }
84488             return ts.visitEachChild(node, visitor, context);
84489         }
84490         function isVariableStatementOfTypeScriptClassWrapper(node) {
84491             return node.declarationList.declarations.length === 1
84492                 && !!node.declarationList.declarations[0].initializer
84493                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84494         }
84495         function visitVariableStatement(node) {
84496             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84497             var updated;
84498             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84499                 // we are inside a converted loop - hoist variable declarations
84500                 var assignments = void 0;
84501                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84502                     var decl = _a[_i];
84503                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84504                     if (decl.initializer) {
84505                         var assignment = void 0;
84506                         if (ts.isBindingPattern(decl.name)) {
84507                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84508                         }
84509                         else {
84510                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84511                             ts.setTextRange(assignment, decl);
84512                         }
84513                         assignments = ts.append(assignments, assignment);
84514                     }
84515                 }
84516                 if (assignments) {
84517                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84518                 }
84519                 else {
84520                     // none of declarations has initializer - the entire variable statement can be deleted
84521                     updated = undefined;
84522                 }
84523             }
84524             else {
84525                 updated = ts.visitEachChild(node, visitor, context);
84526             }
84527             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84528             return updated;
84529         }
84530         /**
84531          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84532          *
84533          * @param node A VariableDeclarationList node.
84534          */
84535         function visitVariableDeclarationList(node) {
84536             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84537                 if (node.flags & 3 /* BlockScoped */) {
84538                     enableSubstitutionsForBlockScopedBindings();
84539                 }
84540                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84541                     ? visitVariableDeclarationInLetDeclarationList
84542                     : visitVariableDeclaration);
84543                 var declarationList = ts.createVariableDeclarationList(declarations);
84544                 ts.setOriginalNode(declarationList, node);
84545                 ts.setTextRange(declarationList, node);
84546                 ts.setCommentRange(declarationList, node);
84547                 // If the first or last declaration is a binding pattern, we need to modify
84548                 // the source map range for the declaration list.
84549                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84550                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84551                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84552                 }
84553                 return declarationList;
84554             }
84555             return ts.visitEachChild(node, visitor, context);
84556         }
84557         function getRangeUnion(declarations) {
84558             // declarations may not be sorted by position.
84559             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84560             var pos = -1, end = -1;
84561             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84562                 var node = declarations_10[_i];
84563                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84564                 end = Math.max(end, node.end);
84565             }
84566             return ts.createRange(pos, end);
84567         }
84568         /**
84569          * Gets a value indicating whether we should emit an explicit initializer for a variable
84570          * declaration in a `let` declaration list.
84571          *
84572          * @param node A VariableDeclaration node.
84573          */
84574         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84575             // Nested let bindings might need to be initialized explicitly to preserve
84576             // ES6 semantic:
84577             //
84578             //  { let x = 1; }
84579             //  { let x; } // x here should be undefined. not 1
84580             //
84581             // Top level bindings never collide with anything and thus don't require
84582             // explicit initialization. As for nested let bindings there are two cases:
84583             //
84584             // - Nested let bindings that were not renamed definitely should be
84585             //   initialized explicitly:
84586             //
84587             //    { let x = 1; }
84588             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84589             //
84590             //   Without explicit initialization code in /*1*/ can be executed even if
84591             //   some-condition is evaluated to false.
84592             //
84593             // - Renaming introduces fresh name that should not collide with any
84594             //   existing names, however renamed bindings sometimes also should be
84595             //   explicitly initialized. One particular case: non-captured binding
84596             //   declared inside loop body (but not in loop initializer):
84597             //
84598             //    let x;
84599             //    for (;;) {
84600             //        let x;
84601             //    }
84602             //
84603             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84604             //   with outer 'x' however it will should be reset on every iteration as
84605             //   if it was declared anew.
84606             //
84607             //   * Why non-captured binding?
84608             //     - Because if loop contains block scoped binding captured in some
84609             //       function then loop body will be rewritten to have a fresh scope
84610             //       on every iteration so everything will just work.
84611             //
84612             //   * Why loop initializer is excluded?
84613             //     - Since we've introduced a fresh name it already will be undefined.
84614             var flags = resolver.getNodeCheckFlags(node);
84615             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84616             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84617             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84618                 || (isCapturedInFunction
84619                     && isDeclaredInLoop
84620                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84621             var emitExplicitInitializer = !emittedAsTopLevel
84622                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84623                 && (!resolver.isDeclarationWithCollidingName(node)
84624                     || (isDeclaredInLoop
84625                         && !isCapturedInFunction
84626                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84627             return emitExplicitInitializer;
84628         }
84629         /**
84630          * Visits a VariableDeclaration in a `let` declaration list.
84631          *
84632          * @param node A VariableDeclaration node.
84633          */
84634         function visitVariableDeclarationInLetDeclarationList(node) {
84635             // For binding pattern names that lack initializers there is no point to emit
84636             // explicit initializer since downlevel codegen for destructuring will fail
84637             // in the absence of initializer so all binding elements will say uninitialized
84638             var name = node.name;
84639             if (ts.isBindingPattern(name)) {
84640                 return visitVariableDeclaration(node);
84641             }
84642             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84643                 var clone_3 = ts.getMutableClone(node);
84644                 clone_3.initializer = ts.createVoidZero();
84645                 return clone_3;
84646             }
84647             return ts.visitEachChild(node, visitor, context);
84648         }
84649         /**
84650          * Visits a VariableDeclaration node with a binding pattern.
84651          *
84652          * @param node A VariableDeclaration node.
84653          */
84654         function visitVariableDeclaration(node) {
84655             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84656             var updated;
84657             if (ts.isBindingPattern(node.name)) {
84658                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84659                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84660             }
84661             else {
84662                 updated = ts.visitEachChild(node, visitor, context);
84663             }
84664             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84665             return updated;
84666         }
84667         function recordLabel(node) {
84668             convertedLoopState.labels.set(ts.idText(node.label), true);
84669         }
84670         function resetLabel(node) {
84671             convertedLoopState.labels.set(ts.idText(node.label), false);
84672         }
84673         function visitLabeledStatement(node) {
84674             if (convertedLoopState && !convertedLoopState.labels) {
84675                 convertedLoopState.labels = ts.createMap();
84676             }
84677             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84678             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84679                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84680                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84681         }
84682         function visitIterationStatement(node, outermostLabeledStatement) {
84683             switch (node.kind) {
84684                 case 228 /* DoStatement */:
84685                 case 229 /* WhileStatement */:
84686                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84687                 case 230 /* ForStatement */:
84688                     return visitForStatement(node, outermostLabeledStatement);
84689                 case 231 /* ForInStatement */:
84690                     return visitForInStatement(node, outermostLabeledStatement);
84691                 case 232 /* ForOfStatement */:
84692                     return visitForOfStatement(node, outermostLabeledStatement);
84693             }
84694         }
84695         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84696             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84697             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84698             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84699             return updated;
84700         }
84701         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84702             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84703         }
84704         function visitForStatement(node, outermostLabeledStatement) {
84705             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84706         }
84707         function visitForInStatement(node, outermostLabeledStatement) {
84708             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84709         }
84710         function visitForOfStatement(node, outermostLabeledStatement) {
84711             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84712         }
84713         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84714             var statements = [];
84715             var initializer = node.initializer;
84716             if (ts.isVariableDeclarationList(initializer)) {
84717                 if (node.initializer.flags & 3 /* BlockScoped */) {
84718                     enableSubstitutionsForBlockScopedBindings();
84719                 }
84720                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84721                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84722                     // This works whether the declaration is a var, let, or const.
84723                     // It will use rhsIterationValue _a[_i] as the initializer.
84724                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84725                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84726                     ts.setOriginalNode(declarationList, node.initializer);
84727                     // Adjust the source map range for the first declaration to align with the old
84728                     // emitter.
84729                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84730                     statements.push(ts.createVariableStatement(
84731                     /*modifiers*/ undefined, declarationList));
84732                 }
84733                 else {
84734                     // The following call does not include the initializer, so we have
84735                     // to emit it separately.
84736                     statements.push(ts.setTextRange(ts.createVariableStatement(
84737                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84738                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84739                         /*type*/ undefined, boundValue)
84740                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84741                 }
84742             }
84743             else {
84744                 // Initializer is an expression. Emit the expression in the body, so that it's
84745                 // evaluated on every iteration.
84746                 var assignment = ts.createAssignment(initializer, boundValue);
84747                 if (ts.isDestructuringAssignment(assignment)) {
84748                     ts.aggregateTransformFlags(assignment);
84749                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84750                 }
84751                 else {
84752                     assignment.end = initializer.end;
84753                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84754                 }
84755             }
84756             if (convertedLoopBodyStatements) {
84757                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84758             }
84759             else {
84760                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84761                 if (ts.isBlock(statement)) {
84762                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84763                 }
84764                 else {
84765                     statements.push(statement);
84766                     return createSyntheticBlockForConvertedStatements(statements);
84767                 }
84768             }
84769         }
84770         function createSyntheticBlockForConvertedStatements(statements) {
84771             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84772             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84773         }
84774         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84775             // The following ES6 code:
84776             //
84777             //    for (let v of expr) { }
84778             //
84779             // should be emitted as
84780             //
84781             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84782             //        var v = _a[_i];
84783             //    }
84784             //
84785             // where _a and _i are temps emitted to capture the RHS and the counter,
84786             // respectively.
84787             // When the left hand side is an expression instead of a let declaration,
84788             // the "let v" is not emitted.
84789             // When the left hand side is a let/const, the v is renamed if there is
84790             // another v in scope.
84791             // Note that all assignments to the LHS are emitted in the body, including
84792             // all destructuring.
84793             // Note also that because an extra statement is needed to assign to the LHS,
84794             // for-of bodies are always emitted as blocks.
84795             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84796             // In the case where the user wrote an identifier as the RHS, like this:
84797             //
84798             //     for (let v of arr) { }
84799             //
84800             // we don't want to emit a temporary variable for the RHS, just use it directly.
84801             var counter = ts.createLoopVariable();
84802             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84803             // The old emitter does not emit source maps for the expression
84804             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84805             var forStatement = ts.setTextRange(ts.createFor(
84806             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84807                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84808                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84809             ]), node.expression), 2097152 /* NoHoisting */), 
84810             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84811             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84812             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84813             /*location*/ node);
84814             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84815             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84816             ts.setTextRange(forStatement, node);
84817             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
84818         }
84819         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
84820             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84821             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84822             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84823             var errorRecord = ts.createUniqueName("e");
84824             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
84825             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
84826             var values = ts.createValuesHelper(context, expression, node.expression);
84827             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
84828             hoistVariableDeclaration(errorRecord);
84829             hoistVariableDeclaration(returnMethod);
84830             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84831             var initializer = ancestorFacts & 1024 /* IterationContainer */
84832                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
84833                 : values;
84834             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
84835             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84836                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
84837                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
84838             ]), node.expression), 2097152 /* NoHoisting */), 
84839             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
84840             /*incrementor*/ ts.createAssignment(result, next), 
84841             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
84842             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84843             return ts.createTry(ts.createBlock([
84844                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
84845             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
84846                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
84847                     ts.createPropertyAssignment("error", catchVariable)
84848                 ])))
84849             ]), 1 /* SingleLine */)), ts.createBlock([
84850                 ts.createTry(
84851                 /*tryBlock*/ ts.createBlock([
84852                     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 */),
84853                 ]), 
84854                 /*catchClause*/ undefined, 
84855                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
84856                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
84857                 ]), 1 /* SingleLine */))
84858             ]));
84859         }
84860         /**
84861          * Visits an ObjectLiteralExpression with computed property names.
84862          *
84863          * @param node An ObjectLiteralExpression node.
84864          */
84865         function visitObjectLiteralExpression(node) {
84866             // We are here because a ComputedPropertyName was used somewhere in the expression.
84867             var properties = node.properties;
84868             var numProperties = properties.length;
84869             // Find the first computed property.
84870             // Everything until that point can be emitted as part of the initial object literal.
84871             var numInitialProperties = numProperties;
84872             var numInitialPropertiesWithoutYield = numProperties;
84873             for (var i = 0; i < numProperties; i++) {
84874                 var property = properties[i];
84875                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
84876                     && i < numInitialPropertiesWithoutYield) {
84877                     numInitialPropertiesWithoutYield = i;
84878                 }
84879                 if (property.name.kind === 154 /* ComputedPropertyName */) {
84880                     numInitialProperties = i;
84881                     break;
84882                 }
84883             }
84884             if (numInitialProperties !== numProperties) {
84885                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
84886                     numInitialProperties = numInitialPropertiesWithoutYield;
84887                 }
84888                 // For computed properties, we need to create a unique handle to the object
84889                 // literal so we can modify it without risking internal assignments tainting the object.
84890                 var temp = ts.createTempVariable(hoistVariableDeclaration);
84891                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
84892                 var expressions = [];
84893                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
84894                 if (node.multiLine) {
84895                     ts.startOnNewLine(assignment);
84896                 }
84897                 expressions.push(assignment);
84898                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
84899                 // We need to clone the temporary identifier so that we can write it on a
84900                 // new line
84901                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
84902                 return ts.inlineExpressions(expressions);
84903             }
84904             return ts.visitEachChild(node, visitor, context);
84905         }
84906         function shouldConvertPartOfIterationStatement(node) {
84907             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
84908         }
84909         function shouldConvertInitializerOfForStatement(node) {
84910             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
84911         }
84912         function shouldConvertConditionOfForStatement(node) {
84913             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
84914         }
84915         function shouldConvertIncrementorOfForStatement(node) {
84916             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
84917         }
84918         function shouldConvertIterationStatement(node) {
84919             return shouldConvertBodyOfIterationStatement(node)
84920                 || shouldConvertInitializerOfForStatement(node);
84921         }
84922         function shouldConvertBodyOfIterationStatement(node) {
84923             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
84924         }
84925         /**
84926          * Records constituents of name for the given variable to be hoisted in the outer scope.
84927          */
84928         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
84929             if (!state.hoistedLocalVariables) {
84930                 state.hoistedLocalVariables = [];
84931             }
84932             visit(node.name);
84933             function visit(node) {
84934                 if (node.kind === 75 /* Identifier */) {
84935                     state.hoistedLocalVariables.push(node);
84936                 }
84937                 else {
84938                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
84939                         var element = _a[_i];
84940                         if (!ts.isOmittedExpression(element)) {
84941                             visit(element.name);
84942                         }
84943                     }
84944                 }
84945             }
84946         }
84947         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
84948             if (!shouldConvertIterationStatement(node)) {
84949                 var saveAllowedNonLabeledJumps = void 0;
84950                 if (convertedLoopState) {
84951                     // we get here if we are trying to emit normal loop loop inside converted loop
84952                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
84953                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
84954                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
84955                 }
84956                 var result = convert
84957                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
84958                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
84959                 if (convertedLoopState) {
84960                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
84961                 }
84962                 return result;
84963             }
84964             var currentState = createConvertedLoopState(node);
84965             var statements = [];
84966             var outerConvertedLoopState = convertedLoopState;
84967             convertedLoopState = currentState;
84968             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
84969             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
84970             convertedLoopState = outerConvertedLoopState;
84971             if (initializerFunction)
84972                 statements.push(initializerFunction.functionDeclaration);
84973             if (bodyFunction)
84974                 statements.push(bodyFunction.functionDeclaration);
84975             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
84976             if (initializerFunction) {
84977                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
84978             }
84979             var loop;
84980             if (bodyFunction) {
84981                 if (convert) {
84982                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
84983                 }
84984                 else {
84985                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
84986                     ts.aggregateTransformFlags(clone_4);
84987                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
84988                 }
84989             }
84990             else {
84991                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
84992                 ts.aggregateTransformFlags(clone_5);
84993                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
84994             }
84995             statements.push(loop);
84996             return statements;
84997         }
84998         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
84999             switch (node.kind) {
85000                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85001                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85002                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85003                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85004                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85005                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85006             }
85007         }
85008         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85009             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85010             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85011             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);
85012         }
85013         function convertForOfStatement(node, convertedLoopBody) {
85014             return ts.updateForOf(node, 
85015             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85016         }
85017         function convertForInStatement(node, convertedLoopBody) {
85018             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85019         }
85020         function convertDoStatement(node, convertedLoopBody) {
85021             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85022         }
85023         function convertWhileStatement(node, convertedLoopBody) {
85024             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85025         }
85026         function createConvertedLoopState(node) {
85027             var loopInitializer;
85028             switch (node.kind) {
85029                 case 230 /* ForStatement */:
85030                 case 231 /* ForInStatement */:
85031                 case 232 /* ForOfStatement */:
85032                     var initializer = node.initializer;
85033                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85034                         loopInitializer = initializer;
85035                     }
85036                     break;
85037             }
85038             // variables that will be passed to the loop as parameters
85039             var loopParameters = [];
85040             // variables declared in the loop initializer that will be changed inside the loop
85041             var loopOutParameters = [];
85042             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85043                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85044                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85045                     var decl = _a[_i];
85046                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85047                 }
85048             }
85049             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85050             if (convertedLoopState) {
85051                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85052                 // if outer converted loop has already accumulated some state - pass it through
85053                 if (convertedLoopState.argumentsName) {
85054                     // outer loop has already used 'arguments' so we've already have some name to alias it
85055                     // use the same name in all nested loops
85056                     currentState.argumentsName = convertedLoopState.argumentsName;
85057                 }
85058                 if (convertedLoopState.thisName) {
85059                     // outer loop has already used 'this' so we've already have some name to alias it
85060                     // use the same name in all nested loops
85061                     currentState.thisName = convertedLoopState.thisName;
85062                 }
85063                 if (convertedLoopState.hoistedLocalVariables) {
85064                     // we've already collected some non-block scoped variable declarations in enclosing loop
85065                     // use the same storage in nested loop
85066                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85067                 }
85068             }
85069             return currentState;
85070         }
85071         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85072             var extraVariableDeclarations;
85073             // propagate state from the inner loop to the outer loop if necessary
85074             if (state.argumentsName) {
85075                 // if alias for arguments is set
85076                 if (outerState) {
85077                     // pass it to outer converted loop
85078                     outerState.argumentsName = state.argumentsName;
85079                 }
85080                 else {
85081                     // this is top level converted loop and we need to create an alias for 'arguments' object
85082                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85083                     /*type*/ undefined, ts.createIdentifier("arguments")));
85084                 }
85085             }
85086             if (state.thisName) {
85087                 // if alias for this is set
85088                 if (outerState) {
85089                     // pass it to outer converted loop
85090                     outerState.thisName = state.thisName;
85091                 }
85092                 else {
85093                     // this is top level converted loop so we need to create an alias for 'this' here
85094                     // NOTE:
85095                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85096                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85097                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85098                     /*type*/ undefined, ts.createIdentifier("this")));
85099                 }
85100             }
85101             if (state.hoistedLocalVariables) {
85102                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85103                 if (outerState) {
85104                     // pass them to outer converted loop
85105                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85106                 }
85107                 else {
85108                     if (!extraVariableDeclarations) {
85109                         extraVariableDeclarations = [];
85110                     }
85111                     // hoist collected variable declarations
85112                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85113                         var identifier = _a[_i];
85114                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85115                     }
85116                 }
85117             }
85118             // add extra variables to hold out parameters if necessary
85119             if (state.loopOutParameters.length) {
85120                 if (!extraVariableDeclarations) {
85121                     extraVariableDeclarations = [];
85122                 }
85123                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85124                     var outParam = _c[_b];
85125                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85126                 }
85127             }
85128             if (state.conditionVariable) {
85129                 if (!extraVariableDeclarations) {
85130                     extraVariableDeclarations = [];
85131                 }
85132                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85133             }
85134             // create variable statement to hold all introduced variable declarations
85135             if (extraVariableDeclarations) {
85136                 statements.push(ts.createVariableStatement(
85137                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85138             }
85139         }
85140         function createOutVariable(p) {
85141             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85142         }
85143         /**
85144          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85145          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85146          * used to preserve the per-iteration environment semantics of
85147          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85148          */
85149         function createFunctionForInitializerOfForStatement(node, currentState) {
85150             var functionName = ts.createUniqueName("_loop_init");
85151             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85152             var emitFlags = 0 /* None */;
85153             if (currentState.containsLexicalThis)
85154                 emitFlags |= 8 /* CapturesThis */;
85155             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85156                 emitFlags |= 262144 /* AsyncFunctionBody */;
85157             var statements = [];
85158             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85159             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85160             // This transforms the following ES2015 syntax:
85161             //
85162             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85163             //      // loop body
85164             //  }
85165             //
85166             // Into the following ES5 syntax:
85167             //
85168             //  var _loop_init_1 = function () {
85169             //      var i = (setImmediate(() => console.log(i)), 0);
85170             //      out_i_1 = i;
85171             //  };
85172             //  var out_i_1;
85173             //  _loop_init_1();
85174             //  for (var i = out_i_1; i < 2; i++) {
85175             //      // loop body
85176             //  }
85177             //
85178             // Which prevents mutations to `i` in the per-iteration environment of the body
85179             // from affecting the initial value for `i` outside of the per-iteration environment.
85180             var functionDeclaration = ts.createVariableStatement(
85181             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85182                 ts.createVariableDeclaration(functionName, 
85183                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85184                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85185                 /*name*/ undefined, 
85186                 /*typeParameters*/ undefined, 
85187                 /*parameters*/ undefined, 
85188                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85189             ]), 2097152 /* NoHoisting */));
85190             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85191             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85192         }
85193         /**
85194          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85195          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85196          * preserve the per-iteration environment semantics of
85197          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85198          */
85199         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85200             var functionName = ts.createUniqueName("_loop");
85201             startLexicalEnvironment();
85202             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85203             var lexicalEnvironment = endLexicalEnvironment();
85204             var statements = [];
85205             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85206                 // If a block-scoped variable declared in the initializer of `node` is captured in
85207                 // the condition or incrementor, we must move the condition and incrementor into
85208                 // the body of the for loop.
85209                 //
85210                 // This transforms the following ES2015 syntax:
85211                 //
85212                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85213                 //      // loop body
85214                 //  }
85215                 //
85216                 // Into the following ES5 syntax:
85217                 //
85218                 //  var _loop_1 = function (i) {
85219                 //      if (inc_1)
85220                 //          setImmediate(() => console.log(i)), i++;
85221                 //      else
85222                 //          inc_1 = true;
85223                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85224                 //          return out_i_1 = i, "break";
85225                 //      // loop body
85226                 //      out_i_1 = i;
85227                 //  }
85228                 //  var out_i_1, inc_1 = false;
85229                 //  for (var i = 0;;) {
85230                 //      var state_1 = _loop_1(i);
85231                 //      i = out_i_1;
85232                 //      if (state_1 === "break")
85233                 //          break;
85234                 //  }
85235                 //
85236                 // Which prevents mutations to `i` in the per-iteration environment of the body
85237                 // from affecting the value of `i` in the previous per-iteration environment.
85238                 //
85239                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85240                 // environment that is carried over to the next iteration of the loop. As a result,
85241                 // we must indicate whether this is the first evaluation of the loop body so that
85242                 // we only evaluate the incrementor on subsequent evaluations.
85243                 currentState.conditionVariable = ts.createUniqueName("inc");
85244                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85245                 if (shouldConvertConditionOfForStatement(node)) {
85246                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85247                 }
85248             }
85249             if (ts.isBlock(statement)) {
85250                 ts.addRange(statements, statement.statements);
85251             }
85252             else {
85253                 statements.push(statement);
85254             }
85255             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85256             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85257             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85258             if (ts.isBlock(statement))
85259                 ts.setOriginalNode(loopBody, statement);
85260             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85261             var emitFlags = 0;
85262             if (currentState.containsLexicalThis)
85263                 emitFlags |= 8 /* CapturesThis */;
85264             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85265                 emitFlags |= 262144 /* AsyncFunctionBody */;
85266             // This transforms the following ES2015 syntax (in addition to other variations):
85267             //
85268             //  for (let i = 0; i < 2; i++) {
85269             //      setImmediate(() => console.log(i));
85270             //  }
85271             //
85272             // Into the following ES5 syntax:
85273             //
85274             //  var _loop_1 = function (i) {
85275             //      setImmediate(() => console.log(i));
85276             //  };
85277             //  for (var i = 0; i < 2; i++) {
85278             //      _loop_1(i);
85279             //  }
85280             var functionDeclaration = ts.createVariableStatement(
85281             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85282                 ts.createVariableDeclaration(functionName, 
85283                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85284                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85285                 /*name*/ undefined, 
85286                 /*typeParameters*/ undefined, currentState.loopParameters, 
85287                 /*type*/ undefined, loopBody), emitFlags))
85288             ]), 2097152 /* NoHoisting */));
85289             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85290             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85291         }
85292         function copyOutParameter(outParam, copyDirection) {
85293             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85294             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85295             return ts.createBinary(target, 62 /* EqualsToken */, source);
85296         }
85297         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85298             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85299                 var outParam = outParams_1[_i];
85300                 if (outParam.flags & partFlags) {
85301                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85302                 }
85303             }
85304         }
85305         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85306             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85307             var callResult = containsYield
85308                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85309                 : call;
85310             return ts.createStatement(callResult);
85311         }
85312         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85313             var statements = [];
85314             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85315             // simple loops are emitted as just 'loop()';
85316             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85317             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85318                 !state.labeledNonLocalBreaks &&
85319                 !state.labeledNonLocalContinues;
85320             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85321             var callResult = containsYield
85322                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85323                 : call;
85324             if (isSimpleLoop) {
85325                 statements.push(ts.createExpressionStatement(callResult));
85326                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85327             }
85328             else {
85329                 var loopResultName = ts.createUniqueName("state");
85330                 var stateVariable = ts.createVariableStatement(
85331                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85332                 statements.push(stateVariable);
85333                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85334                 if (state.nonLocalJumps & 8 /* Return */) {
85335                     var returnStatement = void 0;
85336                     if (outerState) {
85337                         outerState.nonLocalJumps |= 8 /* Return */;
85338                         returnStatement = ts.createReturn(loopResultName);
85339                     }
85340                     else {
85341                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85342                     }
85343                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85344                 }
85345                 if (state.nonLocalJumps & 2 /* Break */) {
85346                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85347                 }
85348                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85349                     var caseClauses = [];
85350                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85351                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85352                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85353                 }
85354             }
85355             return statements;
85356         }
85357         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85358             if (isBreak) {
85359                 if (!state.labeledNonLocalBreaks) {
85360                     state.labeledNonLocalBreaks = ts.createMap();
85361                 }
85362                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85363             }
85364             else {
85365                 if (!state.labeledNonLocalContinues) {
85366                     state.labeledNonLocalContinues = ts.createMap();
85367                 }
85368                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85369             }
85370         }
85371         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85372             if (!table) {
85373                 return;
85374             }
85375             table.forEach(function (labelMarker, labelText) {
85376                 var statements = [];
85377                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85378                 // then emit labeled break\continue
85379                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85380                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85381                     var label = ts.createIdentifier(labelText);
85382                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85383                 }
85384                 else {
85385                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85386                     statements.push(ts.createReturn(loopResultName));
85387                 }
85388                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85389             });
85390         }
85391         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85392             var name = decl.name;
85393             if (ts.isBindingPattern(name)) {
85394                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85395                     var element = _a[_i];
85396                     if (!ts.isOmittedExpression(element)) {
85397                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85398                     }
85399                 }
85400             }
85401             else {
85402                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85403                 var checkFlags = resolver.getNodeCheckFlags(decl);
85404                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85405                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85406                     var flags = 0;
85407                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85408                         flags |= 1 /* Body */;
85409                     }
85410                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85411                         flags |= 2 /* Initializer */;
85412                     }
85413                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85414                 }
85415             }
85416         }
85417         /**
85418          * Adds the members of an object literal to an array of expressions.
85419          *
85420          * @param expressions An array of expressions.
85421          * @param node An ObjectLiteralExpression node.
85422          * @param receiver The receiver for members of the ObjectLiteralExpression.
85423          * @param numInitialNonComputedProperties The number of initial properties without
85424          *                                        computed property names.
85425          */
85426         function addObjectLiteralMembers(expressions, node, receiver, start) {
85427             var properties = node.properties;
85428             var numProperties = properties.length;
85429             for (var i = start; i < numProperties; i++) {
85430                 var property = properties[i];
85431                 switch (property.kind) {
85432                     case 163 /* GetAccessor */:
85433                     case 164 /* SetAccessor */:
85434                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85435                         if (property === accessors.firstAccessor) {
85436                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85437                         }
85438                         break;
85439                     case 161 /* MethodDeclaration */:
85440                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85441                         break;
85442                     case 281 /* PropertyAssignment */:
85443                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85444                         break;
85445                     case 282 /* ShorthandPropertyAssignment */:
85446                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85447                         break;
85448                     default:
85449                         ts.Debug.failBadSyntaxKind(node);
85450                         break;
85451                 }
85452             }
85453         }
85454         /**
85455          * Transforms a PropertyAssignment node into an expression.
85456          *
85457          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85458          * @param property The PropertyAssignment node.
85459          * @param receiver The receiver for the assignment.
85460          */
85461         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85462             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85463             ts.setTextRange(expression, property);
85464             if (startsOnNewLine) {
85465                 ts.startOnNewLine(expression);
85466             }
85467             return expression;
85468         }
85469         /**
85470          * Transforms a ShorthandPropertyAssignment node into an expression.
85471          *
85472          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85473          * @param property The ShorthandPropertyAssignment node.
85474          * @param receiver The receiver for the assignment.
85475          */
85476         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85477             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85478             ts.setTextRange(expression, property);
85479             if (startsOnNewLine) {
85480                 ts.startOnNewLine(expression);
85481             }
85482             return expression;
85483         }
85484         /**
85485          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85486          *
85487          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85488          * @param method The MethodDeclaration node.
85489          * @param receiver The receiver for the assignment.
85490          */
85491         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85492             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85493             ts.setTextRange(expression, method);
85494             if (startsOnNewLine) {
85495                 ts.startOnNewLine(expression);
85496             }
85497             return expression;
85498         }
85499         function visitCatchClause(node) {
85500             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85501             var updated;
85502             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85503             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85504                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85505                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85506                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85507                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85508                 var list = ts.createVariableDeclarationList(vars);
85509                 ts.setTextRange(list, node.variableDeclaration);
85510                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85511                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85512             }
85513             else {
85514                 updated = ts.visitEachChild(node, visitor, context);
85515             }
85516             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85517             return updated;
85518         }
85519         function addStatementToStartOfBlock(block, statement) {
85520             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85521             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85522         }
85523         /**
85524          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85525          * PropertyAssignment.
85526          *
85527          * @param node A MethodDeclaration node.
85528          */
85529         function visitMethodDeclaration(node) {
85530             // We should only get here for methods on an object literal with regular identifier names.
85531             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85532             // Methods with computed property names are handled in visitObjectLiteralExpression.
85533             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85534             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85535             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85536             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85537             /*location*/ node);
85538         }
85539         /**
85540          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85541          *
85542          * @param node An AccessorDeclaration node.
85543          */
85544         function visitAccessorDeclaration(node) {
85545             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85546             var savedConvertedLoopState = convertedLoopState;
85547             convertedLoopState = undefined;
85548             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85549             var updated;
85550             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85551             var body = transformFunctionBody(node);
85552             if (node.kind === 163 /* GetAccessor */) {
85553                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85554             }
85555             else {
85556                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85557             }
85558             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85559             convertedLoopState = savedConvertedLoopState;
85560             return updated;
85561         }
85562         /**
85563          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85564          *
85565          * @param node A ShorthandPropertyAssignment node.
85566          */
85567         function visitShorthandPropertyAssignment(node) {
85568             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85569             /*location*/ node);
85570         }
85571         function visitComputedPropertyName(node) {
85572             return ts.visitEachChild(node, visitor, context);
85573         }
85574         /**
85575          * Visits a YieldExpression node.
85576          *
85577          * @param node A YieldExpression node.
85578          */
85579         function visitYieldExpression(node) {
85580             // `yield` expressions are transformed using the generators transformer.
85581             return ts.visitEachChild(node, visitor, context);
85582         }
85583         /**
85584          * Visits an ArrayLiteralExpression that contains a spread element.
85585          *
85586          * @param node An ArrayLiteralExpression node.
85587          */
85588         function visitArrayLiteralExpression(node) {
85589             if (ts.some(node.elements, ts.isSpreadElement)) {
85590                 // We are here because we contain a SpreadElementExpression.
85591                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85592             }
85593             return ts.visitEachChild(node, visitor, context);
85594         }
85595         /**
85596          * Visits a CallExpression that contains either a spread element or `super`.
85597          *
85598          * @param node a CallExpression.
85599          */
85600         function visitCallExpression(node) {
85601             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85602                 return visitTypeScriptClassWrapper(node);
85603             }
85604             var expression = ts.skipOuterExpressions(node.expression);
85605             if (expression.kind === 102 /* SuperKeyword */ ||
85606                 ts.isSuperProperty(expression) ||
85607                 ts.some(node.arguments, ts.isSpreadElement)) {
85608                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85609             }
85610             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85611             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85612         }
85613         function visitTypeScriptClassWrapper(node) {
85614             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85615             // The wrapper has a form similar to:
85616             //
85617             //  (function() {
85618             //      class C { // 1
85619             //      }
85620             //      C.x = 1; // 2
85621             //      return C;
85622             //  }())
85623             //
85624             // When we transform the class, we end up with something like this:
85625             //
85626             //  (function () {
85627             //      var C = (function () { // 3
85628             //          function C() {
85629             //          }
85630             //          return C; // 4
85631             //      }());
85632             //      C.x = 1;
85633             //      return C;
85634             //  }())
85635             //
85636             // We want to simplify the two nested IIFEs to end up with something like this:
85637             //
85638             //  (function () {
85639             //      function C() {
85640             //      }
85641             //      C.x = 1;
85642             //      return C;
85643             //  }())
85644             // We skip any outer expressions in a number of places to get to the innermost
85645             // expression, but we will restore them later to preserve comments and source maps.
85646             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85647             // The class statements are the statements generated by visiting the first statement with initializer of the
85648             // body (1), while all other statements are added to remainingStatements (2)
85649             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85650             // visit the class body statements outside of any converted loop body.
85651             var savedConvertedLoopState = convertedLoopState;
85652             convertedLoopState = undefined;
85653             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85654             convertedLoopState = savedConvertedLoopState;
85655             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85656             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85657             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85658             // We know there is only one variable declaration here as we verified this in an
85659             // earlier call to isTypeScriptClassWrapper
85660             var variable = varStatement.declarationList.declarations[0];
85661             var initializer = ts.skipOuterExpressions(variable.initializer);
85662             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85663             // we see as an assignment, for example:
85664             //
85665             //  (function () {
85666             //      var C_1;
85667             //      var C = C_1 = (function () {
85668             //          function C() {
85669             //          }
85670             //          C.x = function () { return C_1; }
85671             //          return C;
85672             //      }());
85673             //      C = C_1 = __decorate([dec], C);
85674             //      return C;
85675             //  }())
85676             //
85677             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85678             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85679             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85680             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85681             var funcStatements = func.body.statements;
85682             var classBodyStart = 0;
85683             var classBodyEnd = -1;
85684             var statements = [];
85685             if (aliasAssignment) {
85686                 // If we have a class alias assignment, we need to move it to the down-level constructor
85687                 // function we generated for the class.
85688                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85689                 if (extendsCall) {
85690                     statements.push(extendsCall);
85691                     classBodyStart++;
85692                 }
85693                 // The next statement is the function declaration.
85694                 statements.push(funcStatements[classBodyStart]);
85695                 classBodyStart++;
85696                 // Add the class alias following the declaration.
85697                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85698             }
85699             // Find the trailing 'return' statement (4)
85700             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85701                 classBodyEnd--;
85702             }
85703             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85704             // as we already have one that has been introduced by the 'ts' transformer.
85705             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85706             if (classBodyEnd < -1) {
85707                 // If there were any hoisted declarations following the return statement, we should
85708                 // append them.
85709                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85710             }
85711             // Add the remaining statements of the outer wrapper.
85712             ts.addRange(statements, remainingStatements);
85713             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85714             // after the remaining statements from the 'ts' transformer.
85715             ts.addRange(statements, classStatements, /*start*/ 1);
85716             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85717             // and comment locations.
85718             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85719             /*modifiers*/ undefined, 
85720             /*asteriskToken*/ undefined, 
85721             /*name*/ undefined, 
85722             /*typeParameters*/ undefined, func.parameters, 
85723             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85724             /*typeArguments*/ undefined, call.arguments))));
85725         }
85726         function visitImmediateSuperCallInBody(node) {
85727             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85728         }
85729         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85730             // We are here either because SuperKeyword was used somewhere in the expression, or
85731             // because we contain a SpreadElementExpression.
85732             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85733                 node.expression.kind === 102 /* SuperKeyword */ ||
85734                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85735                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85736                 if (node.expression.kind === 102 /* SuperKeyword */) {
85737                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85738                 }
85739                 var resultingCall = void 0;
85740                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85741                     // [source]
85742                     //      f(...a, b)
85743                     //      x.m(...a, b)
85744                     //      super(...a, b)
85745                     //      super.m(...a, b) // in static
85746                     //      super.m(...a, b) // in instance
85747                     //
85748                     // [output]
85749                     //      f.apply(void 0, a.concat([b]))
85750                     //      (_a = x).m.apply(_a, a.concat([b]))
85751                     //      _super.apply(this, a.concat([b]))
85752                     //      _super.m.apply(this, a.concat([b]))
85753                     //      _super.prototype.m.apply(this, a.concat([b]))
85754                     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));
85755                 }
85756                 else {
85757                     // [source]
85758                     //      super(a)
85759                     //      super.m(a) // in static
85760                     //      super.m(a) // in instance
85761                     //
85762                     // [output]
85763                     //      _super.call(this, a)
85764                     //      _super.m.call(this, a)
85765                     //      _super.prototype.m.call(this, a)
85766                     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), 
85767                     /*location*/ node);
85768                 }
85769                 if (node.expression.kind === 102 /* SuperKeyword */) {
85770                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85771                     resultingCall = assignToCapturedThis
85772                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85773                         : initializer;
85774                 }
85775                 return ts.setOriginalNode(resultingCall, node);
85776             }
85777             return ts.visitEachChild(node, visitor, context);
85778         }
85779         /**
85780          * Visits a NewExpression that contains a spread element.
85781          *
85782          * @param node A NewExpression node.
85783          */
85784         function visitNewExpression(node) {
85785             if (ts.some(node.arguments, ts.isSpreadElement)) {
85786                 // We are here because we contain a SpreadElementExpression.
85787                 // [source]
85788                 //      new C(...a)
85789                 //
85790                 // [output]
85791                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85792                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85793                 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)), 
85794                 /*typeArguments*/ undefined, []);
85795             }
85796             return ts.visitEachChild(node, visitor, context);
85797         }
85798         /**
85799          * Transforms an array of Expression nodes that contains a SpreadExpression.
85800          *
85801          * @param elements The array of Expression nodes.
85802          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85803          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85804          */
85805         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85806             // [source]
85807             //      [a, ...b, c]
85808             //
85809             // [output (downlevelIteration)]
85810             //      __spread([a], b, [c])
85811             //
85812             // [output]
85813             //      __spreadArrays([a], b, [c])
85814             // Map spans of spread expressions into their expressions and spans of other
85815             // expressions into an array literal.
85816             var numElements = elements.length;
85817             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
85818                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
85819             }));
85820             if (compilerOptions.downlevelIteration) {
85821                 if (segments.length === 1) {
85822                     var firstSegment = segments[0];
85823                     if (isCallToHelper(firstSegment, "___spread")) {
85824                         return segments[0];
85825                     }
85826                 }
85827                 return ts.createSpreadHelper(context, segments);
85828             }
85829             else {
85830                 if (segments.length === 1) {
85831                     var firstSegment = segments[0];
85832                     if (!needsUniqueCopy
85833                         || isPackedArrayLiteral(firstSegment)
85834                         || isCallToHelper(firstSegment, "___spreadArrays")) {
85835                         return segments[0];
85836                     }
85837                 }
85838                 return ts.createSpreadArraysHelper(context, segments);
85839             }
85840         }
85841         function isPackedElement(node) {
85842             return !ts.isOmittedExpression(node);
85843         }
85844         function isPackedArrayLiteral(node) {
85845             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
85846         }
85847         function isCallToHelper(firstSegment, helperName) {
85848             return ts.isCallExpression(firstSegment)
85849                 && ts.isIdentifier(firstSegment.expression)
85850                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
85851                 && firstSegment.expression.escapedText === helperName;
85852         }
85853         function partitionSpread(node) {
85854             return ts.isSpreadElement(node)
85855                 ? visitSpanOfSpreads
85856                 : visitSpanOfNonSpreads;
85857         }
85858         function visitSpanOfSpreads(chunk) {
85859             return ts.map(chunk, visitExpressionOfSpread);
85860         }
85861         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
85862             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
85863         }
85864         function visitSpreadElement(node) {
85865             return ts.visitNode(node.expression, visitor, ts.isExpression);
85866         }
85867         /**
85868          * Transforms the expression of a SpreadExpression node.
85869          *
85870          * @param node A SpreadExpression node.
85871          */
85872         function visitExpressionOfSpread(node) {
85873             return ts.visitNode(node.expression, visitor, ts.isExpression);
85874         }
85875         /**
85876          * Visits a template literal.
85877          *
85878          * @param node A template literal.
85879          */
85880         function visitTemplateLiteral(node) {
85881             return ts.setTextRange(ts.createLiteral(node.text), node);
85882         }
85883         /**
85884          * Visits a string literal with an extended unicode escape.
85885          *
85886          * @param node A string literal.
85887          */
85888         function visitStringLiteral(node) {
85889             if (node.hasExtendedUnicodeEscape) {
85890                 return ts.setTextRange(ts.createLiteral(node.text), node);
85891             }
85892             return node;
85893         }
85894         /**
85895          * Visits a binary or octal (ES6) numeric literal.
85896          *
85897          * @param node A string literal.
85898          */
85899         function visitNumericLiteral(node) {
85900             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
85901                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
85902             }
85903             return node;
85904         }
85905         /**
85906          * Visits a TaggedTemplateExpression node.
85907          *
85908          * @param node A TaggedTemplateExpression node.
85909          */
85910         function visitTaggedTemplateExpression(node) {
85911             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
85912         }
85913         /**
85914          * Visits a TemplateExpression node.
85915          *
85916          * @param node A TemplateExpression node.
85917          */
85918         function visitTemplateExpression(node) {
85919             var expressions = [];
85920             addTemplateHead(expressions, node);
85921             addTemplateSpans(expressions, node);
85922             // createAdd will check if each expression binds less closely than binary '+'.
85923             // If it does, it wraps the expression in parentheses. Otherwise, something like
85924             //    `abc${ 1 << 2 }`
85925             // becomes
85926             //    "abc" + 1 << 2 + ""
85927             // which is really
85928             //    ("abc" + 1) << (2 + "")
85929             // rather than
85930             //    "abc" + (1 << 2) + ""
85931             var expression = ts.reduceLeft(expressions, ts.createAdd);
85932             if (ts.nodeIsSynthesized(expression)) {
85933                 expression.pos = node.pos;
85934                 expression.end = node.end;
85935             }
85936             return expression;
85937         }
85938         /**
85939          * Gets a value indicating whether we need to include the head of a TemplateExpression.
85940          *
85941          * @param node A TemplateExpression node.
85942          */
85943         function shouldAddTemplateHead(node) {
85944             // If this expression has an empty head literal and the first template span has a non-empty
85945             // literal, then emitting the empty head literal is not necessary.
85946             //     `${ foo } and ${ bar }`
85947             // can be emitted as
85948             //     foo + " and " + bar
85949             // This is because it is only required that one of the first two operands in the emit
85950             // output must be a string literal, so that the other operand and all following operands
85951             // are forced into strings.
85952             //
85953             // If the first template span has an empty literal, then the head must still be emitted.
85954             //     `${ foo }${ bar }`
85955             // must still be emitted as
85956             //     "" + foo + bar
85957             // There is always atleast one templateSpan in this code path, since
85958             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
85959             ts.Debug.assert(node.templateSpans.length !== 0);
85960             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
85961         }
85962         /**
85963          * Adds the head of a TemplateExpression to an array of expressions.
85964          *
85965          * @param expressions An array of expressions.
85966          * @param node A TemplateExpression node.
85967          */
85968         function addTemplateHead(expressions, node) {
85969             if (!shouldAddTemplateHead(node)) {
85970                 return;
85971             }
85972             expressions.push(ts.createLiteral(node.head.text));
85973         }
85974         /**
85975          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
85976          *
85977          * @param expressions An array of expressions.
85978          * @param node A TemplateExpression node.
85979          */
85980         function addTemplateSpans(expressions, node) {
85981             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
85982                 var span = _a[_i];
85983                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
85984                 // Only emit if the literal is non-empty.
85985                 // The binary '+' operator is left-associative, so the first string concatenation
85986                 // with the head will force the result up to this point to be a string.
85987                 // Emitting a '+ ""' has no semantic effect for middles and tails.
85988                 if (span.literal.text.length !== 0) {
85989                     expressions.push(ts.createLiteral(span.literal.text));
85990                 }
85991             }
85992         }
85993         /**
85994          * Visits the `super` keyword
85995          */
85996         function visitSuperKeyword(isExpressionOfCall) {
85997             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
85998                 ts.createFileLevelUniqueName("_super");
85999         }
86000         function visitMetaProperty(node) {
86001             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86002                 hierarchyFacts |= 16384 /* NewTarget */;
86003                 return ts.createFileLevelUniqueName("_newTarget");
86004             }
86005             return node;
86006         }
86007         /**
86008          * Called by the printer just before a node is printed.
86009          *
86010          * @param hint A hint as to the intended usage of the node.
86011          * @param node The node to be printed.
86012          * @param emitCallback The callback used to emit the node.
86013          */
86014         function onEmitNode(hint, node, emitCallback) {
86015             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86016                 // If we are tracking a captured `this`, keep track of the enclosing function.
86017                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86018                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86019                     : 65 /* FunctionIncludes */);
86020                 previousOnEmitNode(hint, node, emitCallback);
86021                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86022                 return;
86023             }
86024             previousOnEmitNode(hint, node, emitCallback);
86025         }
86026         /**
86027          * Enables a more costly code path for substitutions when we determine a source file
86028          * contains block-scoped bindings (e.g. `let` or `const`).
86029          */
86030         function enableSubstitutionsForBlockScopedBindings() {
86031             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86032                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86033                 context.enableSubstitution(75 /* Identifier */);
86034             }
86035         }
86036         /**
86037          * Enables a more costly code path for substitutions when we determine a source file
86038          * contains a captured `this`.
86039          */
86040         function enableSubstitutionsForCapturedThis() {
86041             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86042                 enabledSubstitutions |= 1 /* CapturedThis */;
86043                 context.enableSubstitution(104 /* ThisKeyword */);
86044                 context.enableEmitNotification(162 /* Constructor */);
86045                 context.enableEmitNotification(161 /* MethodDeclaration */);
86046                 context.enableEmitNotification(163 /* GetAccessor */);
86047                 context.enableEmitNotification(164 /* SetAccessor */);
86048                 context.enableEmitNotification(202 /* ArrowFunction */);
86049                 context.enableEmitNotification(201 /* FunctionExpression */);
86050                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86051             }
86052         }
86053         /**
86054          * Hooks node substitutions.
86055          *
86056          * @param hint The context for the emitter.
86057          * @param node The node to substitute.
86058          */
86059         function onSubstituteNode(hint, node) {
86060             node = previousOnSubstituteNode(hint, node);
86061             if (hint === 1 /* Expression */) {
86062                 return substituteExpression(node);
86063             }
86064             if (ts.isIdentifier(node)) {
86065                 return substituteIdentifier(node);
86066             }
86067             return node;
86068         }
86069         /**
86070          * Hooks substitutions for non-expression identifiers.
86071          */
86072         function substituteIdentifier(node) {
86073             // Only substitute the identifier if we have enabled substitutions for block-scoped
86074             // bindings.
86075             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86076                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86077                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86078                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86079                 }
86080             }
86081             return node;
86082         }
86083         /**
86084          * Determines whether a name is the name of a declaration with a colliding name.
86085          * NOTE: This function expects to be called with an original source tree node.
86086          *
86087          * @param node An original source tree node.
86088          */
86089         function isNameOfDeclarationWithCollidingName(node) {
86090             switch (node.parent.kind) {
86091                 case 191 /* BindingElement */:
86092                 case 245 /* ClassDeclaration */:
86093                 case 248 /* EnumDeclaration */:
86094                 case 242 /* VariableDeclaration */:
86095                     return node.parent.name === node
86096                         && resolver.isDeclarationWithCollidingName(node.parent);
86097             }
86098             return false;
86099         }
86100         /**
86101          * Substitutes an expression.
86102          *
86103          * @param node An Expression node.
86104          */
86105         function substituteExpression(node) {
86106             switch (node.kind) {
86107                 case 75 /* Identifier */:
86108                     return substituteExpressionIdentifier(node);
86109                 case 104 /* ThisKeyword */:
86110                     return substituteThisKeyword(node);
86111             }
86112             return node;
86113         }
86114         /**
86115          * Substitutes an expression identifier.
86116          *
86117          * @param node An Identifier node.
86118          */
86119         function substituteExpressionIdentifier(node) {
86120             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86121                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86122                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86123                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86124                 }
86125             }
86126             return node;
86127         }
86128         function isPartOfClassBody(declaration, node) {
86129             var currentNode = ts.getParseTreeNode(node);
86130             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86131                 // if the node has no correlation to a parse tree node, its definitely not
86132                 // part of the body.
86133                 // if the node is outside of the document range of the declaration, its
86134                 // definitely not part of the body.
86135                 return false;
86136             }
86137             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86138             while (currentNode) {
86139                 if (currentNode === blockScope || currentNode === declaration) {
86140                     // if we are in the enclosing block scope of the declaration, we are definitely
86141                     // not inside the class body.
86142                     return false;
86143                 }
86144                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86145                     return true;
86146                 }
86147                 currentNode = currentNode.parent;
86148             }
86149             return false;
86150         }
86151         /**
86152          * Substitutes `this` when contained within an arrow function.
86153          *
86154          * @param node The ThisKeyword node.
86155          */
86156         function substituteThisKeyword(node) {
86157             if (enabledSubstitutions & 1 /* CapturedThis */
86158                 && hierarchyFacts & 16 /* CapturesThis */) {
86159                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86160             }
86161             return node;
86162         }
86163         function getClassMemberPrefix(node, member) {
86164             return ts.hasModifier(member, 32 /* Static */)
86165                 ? ts.getInternalName(node)
86166                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86167         }
86168         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86169             if (!constructor || !hasExtendsClause) {
86170                 return false;
86171             }
86172             if (ts.some(constructor.parameters)) {
86173                 return false;
86174             }
86175             var statement = ts.firstOrUndefined(constructor.body.statements);
86176             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86177                 return false;
86178             }
86179             var statementExpression = statement.expression;
86180             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86181                 return false;
86182             }
86183             var callTarget = statementExpression.expression;
86184             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86185                 return false;
86186             }
86187             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86188             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86189                 return false;
86190             }
86191             var expression = callArgument.expression;
86192             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86193         }
86194     }
86195     ts.transformES2015 = transformES2015;
86196     function createExtendsHelper(context, name) {
86197         context.requestEmitHelper(ts.extendsHelper);
86198         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86199         /*typeArguments*/ undefined, [
86200             name,
86201             ts.createFileLevelUniqueName("_super")
86202         ]);
86203     }
86204     ts.extendsHelper = {
86205         name: "typescript:extends",
86206         importName: "__extends",
86207         scoped: false,
86208         priority: 0,
86209         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            })();"
86210     };
86211 })(ts || (ts = {}));
86212 /*@internal*/
86213 var ts;
86214 (function (ts) {
86215     /**
86216      * Transforms ES5 syntax into ES3 syntax.
86217      *
86218      * @param context Context and state information for the transformation.
86219      */
86220     function transformES5(context) {
86221         var compilerOptions = context.getCompilerOptions();
86222         // enable emit notification only if using --jsx preserve or react-native
86223         var previousOnEmitNode;
86224         var noSubstitution;
86225         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86226             previousOnEmitNode = context.onEmitNode;
86227             context.onEmitNode = onEmitNode;
86228             context.enableEmitNotification(268 /* JsxOpeningElement */);
86229             context.enableEmitNotification(269 /* JsxClosingElement */);
86230             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86231             noSubstitution = [];
86232         }
86233         var previousOnSubstituteNode = context.onSubstituteNode;
86234         context.onSubstituteNode = onSubstituteNode;
86235         context.enableSubstitution(194 /* PropertyAccessExpression */);
86236         context.enableSubstitution(281 /* PropertyAssignment */);
86237         return ts.chainBundle(transformSourceFile);
86238         /**
86239          * Transforms an ES5 source file to ES3.
86240          *
86241          * @param node A SourceFile
86242          */
86243         function transformSourceFile(node) {
86244             return node;
86245         }
86246         /**
86247          * Called by the printer just before a node is printed.
86248          *
86249          * @param hint A hint as to the intended usage of the node.
86250          * @param node The node to emit.
86251          * @param emitCallback A callback used to emit the node.
86252          */
86253         function onEmitNode(hint, node, emitCallback) {
86254             switch (node.kind) {
86255                 case 268 /* JsxOpeningElement */:
86256                 case 269 /* JsxClosingElement */:
86257                 case 267 /* JsxSelfClosingElement */:
86258                     var tagName = node.tagName;
86259                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86260                     break;
86261             }
86262             previousOnEmitNode(hint, node, emitCallback);
86263         }
86264         /**
86265          * Hooks node substitutions.
86266          *
86267          * @param hint A hint as to the intended usage of the node.
86268          * @param node The node to substitute.
86269          */
86270         function onSubstituteNode(hint, node) {
86271             if (node.id && noSubstitution && noSubstitution[node.id]) {
86272                 return previousOnSubstituteNode(hint, node);
86273             }
86274             node = previousOnSubstituteNode(hint, node);
86275             if (ts.isPropertyAccessExpression(node)) {
86276                 return substitutePropertyAccessExpression(node);
86277             }
86278             else if (ts.isPropertyAssignment(node)) {
86279                 return substitutePropertyAssignment(node);
86280             }
86281             return node;
86282         }
86283         /**
86284          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86285          *
86286          * @param node A PropertyAccessExpression
86287          */
86288         function substitutePropertyAccessExpression(node) {
86289             if (ts.isPrivateIdentifier(node.name)) {
86290                 return node;
86291             }
86292             var literalName = trySubstituteReservedName(node.name);
86293             if (literalName) {
86294                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86295             }
86296             return node;
86297         }
86298         /**
86299          * Substitutes a PropertyAssignment whose name is a reserved word.
86300          *
86301          * @param node A PropertyAssignment
86302          */
86303         function substitutePropertyAssignment(node) {
86304             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86305             if (literalName) {
86306                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86307             }
86308             return node;
86309         }
86310         /**
86311          * If an identifier name is a reserved word, returns a string literal for the name.
86312          *
86313          * @param name An Identifier
86314          */
86315         function trySubstituteReservedName(name) {
86316             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86317             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86318                 return ts.setTextRange(ts.createLiteral(name), name);
86319             }
86320             return undefined;
86321         }
86322     }
86323     ts.transformES5 = transformES5;
86324 })(ts || (ts = {}));
86325 // Transforms generator functions into a compatible ES5 representation with similar runtime
86326 // semantics. This is accomplished by first transforming the body of each generator
86327 // function into an intermediate representation that is the compiled into a JavaScript
86328 // switch statement.
86329 //
86330 // Many functions in this transformer will contain comments indicating the expected
86331 // intermediate representation. For illustrative purposes, the following intermediate
86332 // language is used to define this intermediate representation:
86333 //
86334 //  .nop                            - Performs no operation.
86335 //  .local NAME, ...                - Define local variable declarations.
86336 //  .mark LABEL                     - Mark the location of a label.
86337 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86338 //                                    region, all .finally blocks are executed.
86339 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86340 //                                    If jumping out of a protected region, all .finally
86341 //                                    blocks are executed.
86342 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86343 //                                    If jumping out of a protected region, all .finally
86344 //                                    blocks are executed.
86345 //  .yield (x)                      - Yield the value of the optional expression `x`.
86346 //                                    Resume at the next label.
86347 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86348 //                                    expression `x`. Resume at the next label.
86349 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86350 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86351 //                                    "break" abrupt completions jump to the CONTINUE or
86352 //                                    BREAK labels, respectively.
86353 //  .endloop                        - Marks the end of a loop.
86354 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86355 //                                    the supplied expression.
86356 //  .endwith                        - Marks the end of a WithStatement.
86357 //  .switch                         - Marks the beginning of a SwitchStatement.
86358 //  .endswitch                      - Marks the end of a SwitchStatement.
86359 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86360 //                                    supplied name.
86361 //  .endlabeled                     - Marks the end of a LabeledStatement.
86362 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86363 //                                    labels for each block.
86364 //  .catch (x)                      - Marks the beginning of a catch block.
86365 //  .finally                        - Marks the beginning of a finally block.
86366 //  .endfinally                     - Marks the end of a finally block.
86367 //  .endtry                         - Marks the end of a protected region.
86368 //  .throw (x)                      - Throws the value of the expression `x`.
86369 //  .return (x)                     - Returns the value of the expression `x`.
86370 //
86371 // In addition, the illustrative intermediate representation introduces some special
86372 // variables:
86373 //
86374 //  %sent%                          - Either returns the next value sent to the generator,
86375 //                                    returns the result of a delegated yield, or throws
86376 //                                    the exception sent to the generator.
86377 //  %error%                         - Returns the value of the current exception in a
86378 //                                    catch block.
86379 //
86380 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86381 // compilation output looks something like the following:
86382 //
86383 //  function f() {
86384 //      var /*locals*/;
86385 //      /*functions*/
86386 //      return __generator(function (state) {
86387 //          switch (state.label) {
86388 //              /*cases per label*/
86389 //          }
86390 //      });
86391 //  }
86392 //
86393 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86394 //
86395 //  .local NAME                   | var NAME;
86396 // -------------------------------|----------------------------------------------
86397 //  .mark LABEL                   | case LABEL:
86398 // -------------------------------|----------------------------------------------
86399 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86400 // -------------------------------|----------------------------------------------
86401 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86402 // -------------------------------|----------------------------------------------
86403 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86404 // -------------------------------|----------------------------------------------
86405 //  .yield (x)                    |     return [4 /*yield*/, x];
86406 //  .mark RESUME                  | case RESUME:
86407 //      a = %sent%;               |     a = state.sent();
86408 // -------------------------------|----------------------------------------------
86409 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86410 //  .mark RESUME                  | case RESUME:
86411 //      a = %sent%;               |     a = state.sent();
86412 // -------------------------------|----------------------------------------------
86413 //  .with (_a)                    |     with (_a) {
86414 //      a();                      |         a();
86415 //                                |     }
86416 //                                |     state.label = LABEL;
86417 //  .mark LABEL                   | case LABEL:
86418 //                                |     with (_a) {
86419 //      b();                      |         b();
86420 //                                |     }
86421 //  .endwith                      |
86422 // -------------------------------|----------------------------------------------
86423 //                                | case 0:
86424 //                                |     state.trys = [];
86425 //                                | ...
86426 //  .try TRY, CATCH, FINALLY, END |
86427 //  .mark TRY                     | case TRY:
86428 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86429 //  .nop                          |
86430 //      a();                      |     a();
86431 //  .br END                       |     return [3 /*break*/, END];
86432 //  .catch (e)                    |
86433 //  .mark CATCH                   | case CATCH:
86434 //                                |     e = state.sent();
86435 //      b();                      |     b();
86436 //  .br END                       |     return [3 /*break*/, END];
86437 //  .finally                      |
86438 //  .mark FINALLY                 | case FINALLY:
86439 //      c();                      |     c();
86440 //  .endfinally                   |     return [7 /*endfinally*/];
86441 //  .endtry                       |
86442 //  .mark END                     | case END:
86443 /*@internal*/
86444 var ts;
86445 (function (ts) {
86446     var OpCode;
86447     (function (OpCode) {
86448         OpCode[OpCode["Nop"] = 0] = "Nop";
86449         OpCode[OpCode["Statement"] = 1] = "Statement";
86450         OpCode[OpCode["Assign"] = 2] = "Assign";
86451         OpCode[OpCode["Break"] = 3] = "Break";
86452         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86453         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86454         OpCode[OpCode["Yield"] = 6] = "Yield";
86455         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86456         OpCode[OpCode["Return"] = 8] = "Return";
86457         OpCode[OpCode["Throw"] = 9] = "Throw";
86458         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86459     })(OpCode || (OpCode = {}));
86460     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86461     var BlockAction;
86462     (function (BlockAction) {
86463         BlockAction[BlockAction["Open"] = 0] = "Open";
86464         BlockAction[BlockAction["Close"] = 1] = "Close";
86465     })(BlockAction || (BlockAction = {}));
86466     // the kind for a generated code block in a FunctionBuilder
86467     var CodeBlockKind;
86468     (function (CodeBlockKind) {
86469         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86470         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86471         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86472         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86473         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86474     })(CodeBlockKind || (CodeBlockKind = {}));
86475     // the state for a generated code exception block
86476     var ExceptionBlockState;
86477     (function (ExceptionBlockState) {
86478         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86479         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86480         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86481         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86482     })(ExceptionBlockState || (ExceptionBlockState = {}));
86483     // NOTE: changes to this enum should be reflected in the __generator helper.
86484     var Instruction;
86485     (function (Instruction) {
86486         Instruction[Instruction["Next"] = 0] = "Next";
86487         Instruction[Instruction["Throw"] = 1] = "Throw";
86488         Instruction[Instruction["Return"] = 2] = "Return";
86489         Instruction[Instruction["Break"] = 3] = "Break";
86490         Instruction[Instruction["Yield"] = 4] = "Yield";
86491         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86492         Instruction[Instruction["Catch"] = 6] = "Catch";
86493         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86494     })(Instruction || (Instruction = {}));
86495     function getInstructionName(instruction) {
86496         switch (instruction) {
86497             case 2 /* Return */: return "return";
86498             case 3 /* Break */: return "break";
86499             case 4 /* Yield */: return "yield";
86500             case 5 /* YieldStar */: return "yield*";
86501             case 7 /* Endfinally */: return "endfinally";
86502             default: return undefined; // TODO: GH#18217
86503         }
86504     }
86505     function transformGenerators(context) {
86506         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86507         var compilerOptions = context.getCompilerOptions();
86508         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86509         var resolver = context.getEmitResolver();
86510         var previousOnSubstituteNode = context.onSubstituteNode;
86511         context.onSubstituteNode = onSubstituteNode;
86512         var renamedCatchVariables;
86513         var renamedCatchVariableDeclarations;
86514         var inGeneratorFunctionBody;
86515         var inStatementContainingYield;
86516         // The following three arrays store information about generated code blocks.
86517         // All three arrays are correlated by their index. This approach is used over allocating
86518         // objects to store the same information to avoid GC overhead.
86519         //
86520         var blocks; // Information about the code block
86521         var blockOffsets; // The operation offset at which a code block begins or ends
86522         var blockActions; // Whether the code block is opened or closed
86523         var blockStack; // A stack of currently open code blocks
86524         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86525         // operation. These are translated into case clauses in a switch statement.
86526         // The following two arrays are correlated by their index. This approach is used over
86527         // allocating objects to store the same information to avoid GC overhead.
86528         //
86529         var labelOffsets; // The operation offset at which the label is defined.
86530         var labelExpressions; // The NumericLiteral nodes bound to each label.
86531         var nextLabelId = 1; // The next label id to use.
86532         // Operations store information about generated code for the function body. This
86533         // Includes things like statements, assignments, breaks (jumps), and yields.
86534         // The following three arrays are correlated by their index. This approach is used over
86535         // allocating objects to store the same information to avoid GC overhead.
86536         //
86537         var operations; // The operation to perform.
86538         var operationArguments; // The arguments to the operation.
86539         var operationLocations; // The source map location for the operation.
86540         var state; // The name of the state object used by the generator at runtime.
86541         // The following variables store information used by the `build` function:
86542         //
86543         var blockIndex = 0; // The index of the current block.
86544         var labelNumber = 0; // The current label number.
86545         var labelNumbers;
86546         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86547         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86548         var clauses; // The case clauses generated for labels.
86549         var statements; // The statements for the current label.
86550         var exceptionBlockStack; // A stack of containing exception blocks.
86551         var currentExceptionBlock; // The current exception block.
86552         var withBlockStack; // A stack containing `with` blocks.
86553         return ts.chainBundle(transformSourceFile);
86554         function transformSourceFile(node) {
86555             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86556                 return node;
86557             }
86558             var visited = ts.visitEachChild(node, visitor, context);
86559             ts.addEmitHelpers(visited, context.readEmitHelpers());
86560             return visited;
86561         }
86562         /**
86563          * Visits a node.
86564          *
86565          * @param node The node to visit.
86566          */
86567         function visitor(node) {
86568             var transformFlags = node.transformFlags;
86569             if (inStatementContainingYield) {
86570                 return visitJavaScriptInStatementContainingYield(node);
86571             }
86572             else if (inGeneratorFunctionBody) {
86573                 return visitJavaScriptInGeneratorFunctionBody(node);
86574             }
86575             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86576                 return visitGenerator(node);
86577             }
86578             else if (transformFlags & 512 /* ContainsGenerator */) {
86579                 return ts.visitEachChild(node, visitor, context);
86580             }
86581             else {
86582                 return node;
86583             }
86584         }
86585         /**
86586          * Visits a node that is contained within a statement that contains yield.
86587          *
86588          * @param node The node to visit.
86589          */
86590         function visitJavaScriptInStatementContainingYield(node) {
86591             switch (node.kind) {
86592                 case 228 /* DoStatement */:
86593                     return visitDoStatement(node);
86594                 case 229 /* WhileStatement */:
86595                     return visitWhileStatement(node);
86596                 case 237 /* SwitchStatement */:
86597                     return visitSwitchStatement(node);
86598                 case 238 /* LabeledStatement */:
86599                     return visitLabeledStatement(node);
86600                 default:
86601                     return visitJavaScriptInGeneratorFunctionBody(node);
86602             }
86603         }
86604         /**
86605          * Visits a node that is contained within a generator function.
86606          *
86607          * @param node The node to visit.
86608          */
86609         function visitJavaScriptInGeneratorFunctionBody(node) {
86610             switch (node.kind) {
86611                 case 244 /* FunctionDeclaration */:
86612                     return visitFunctionDeclaration(node);
86613                 case 201 /* FunctionExpression */:
86614                     return visitFunctionExpression(node);
86615                 case 163 /* GetAccessor */:
86616                 case 164 /* SetAccessor */:
86617                     return visitAccessorDeclaration(node);
86618                 case 225 /* VariableStatement */:
86619                     return visitVariableStatement(node);
86620                 case 230 /* ForStatement */:
86621                     return visitForStatement(node);
86622                 case 231 /* ForInStatement */:
86623                     return visitForInStatement(node);
86624                 case 234 /* BreakStatement */:
86625                     return visitBreakStatement(node);
86626                 case 233 /* ContinueStatement */:
86627                     return visitContinueStatement(node);
86628                 case 235 /* ReturnStatement */:
86629                     return visitReturnStatement(node);
86630                 default:
86631                     if (node.transformFlags & 262144 /* ContainsYield */) {
86632                         return visitJavaScriptContainingYield(node);
86633                     }
86634                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86635                         return ts.visitEachChild(node, visitor, context);
86636                     }
86637                     else {
86638                         return node;
86639                     }
86640             }
86641         }
86642         /**
86643          * Visits a node that contains a YieldExpression.
86644          *
86645          * @param node The node to visit.
86646          */
86647         function visitJavaScriptContainingYield(node) {
86648             switch (node.kind) {
86649                 case 209 /* BinaryExpression */:
86650                     return visitBinaryExpression(node);
86651                 case 210 /* ConditionalExpression */:
86652                     return visitConditionalExpression(node);
86653                 case 212 /* YieldExpression */:
86654                     return visitYieldExpression(node);
86655                 case 192 /* ArrayLiteralExpression */:
86656                     return visitArrayLiteralExpression(node);
86657                 case 193 /* ObjectLiteralExpression */:
86658                     return visitObjectLiteralExpression(node);
86659                 case 195 /* ElementAccessExpression */:
86660                     return visitElementAccessExpression(node);
86661                 case 196 /* CallExpression */:
86662                     return visitCallExpression(node);
86663                 case 197 /* NewExpression */:
86664                     return visitNewExpression(node);
86665                 default:
86666                     return ts.visitEachChild(node, visitor, context);
86667             }
86668         }
86669         /**
86670          * Visits a generator function.
86671          *
86672          * @param node The node to visit.
86673          */
86674         function visitGenerator(node) {
86675             switch (node.kind) {
86676                 case 244 /* FunctionDeclaration */:
86677                     return visitFunctionDeclaration(node);
86678                 case 201 /* FunctionExpression */:
86679                     return visitFunctionExpression(node);
86680                 default:
86681                     return ts.Debug.failBadSyntaxKind(node);
86682             }
86683         }
86684         /**
86685          * Visits a function declaration.
86686          *
86687          * This will be called when one of the following conditions are met:
86688          * - The function declaration is a generator function.
86689          * - The function declaration is contained within the body of a generator function.
86690          *
86691          * @param node The node to visit.
86692          */
86693         function visitFunctionDeclaration(node) {
86694             // Currently, we only support generators that were originally async functions.
86695             if (node.asteriskToken) {
86696                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86697                 /*decorators*/ undefined, node.modifiers, 
86698                 /*asteriskToken*/ undefined, node.name, 
86699                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86700                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86701                 /*location*/ node), node);
86702             }
86703             else {
86704                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86705                 var savedInStatementContainingYield = inStatementContainingYield;
86706                 inGeneratorFunctionBody = false;
86707                 inStatementContainingYield = false;
86708                 node = ts.visitEachChild(node, visitor, context);
86709                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86710                 inStatementContainingYield = savedInStatementContainingYield;
86711             }
86712             if (inGeneratorFunctionBody) {
86713                 // Function declarations in a generator function body are hoisted
86714                 // to the top of the lexical scope and elided from the current statement.
86715                 hoistFunctionDeclaration(node);
86716                 return undefined;
86717             }
86718             else {
86719                 return node;
86720             }
86721         }
86722         /**
86723          * Visits a function expression.
86724          *
86725          * This will be called when one of the following conditions are met:
86726          * - The function expression is a generator function.
86727          * - The function expression is contained within the body of a generator function.
86728          *
86729          * @param node The node to visit.
86730          */
86731         function visitFunctionExpression(node) {
86732             // Currently, we only support generators that were originally async functions.
86733             if (node.asteriskToken) {
86734                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86735                 /*modifiers*/ undefined, 
86736                 /*asteriskToken*/ undefined, node.name, 
86737                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86738                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86739                 /*location*/ node), node);
86740             }
86741             else {
86742                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86743                 var savedInStatementContainingYield = inStatementContainingYield;
86744                 inGeneratorFunctionBody = false;
86745                 inStatementContainingYield = false;
86746                 node = ts.visitEachChild(node, visitor, context);
86747                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86748                 inStatementContainingYield = savedInStatementContainingYield;
86749             }
86750             return node;
86751         }
86752         /**
86753          * Visits a get or set accessor declaration.
86754          *
86755          * This will be called when one of the following conditions are met:
86756          * - The accessor is contained within the body of a generator function.
86757          *
86758          * @param node The node to visit.
86759          */
86760         function visitAccessorDeclaration(node) {
86761             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86762             var savedInStatementContainingYield = inStatementContainingYield;
86763             inGeneratorFunctionBody = false;
86764             inStatementContainingYield = false;
86765             node = ts.visitEachChild(node, visitor, context);
86766             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86767             inStatementContainingYield = savedInStatementContainingYield;
86768             return node;
86769         }
86770         /**
86771          * Transforms the body of a generator function declaration.
86772          *
86773          * @param node The function body to transform.
86774          */
86775         function transformGeneratorFunctionBody(body) {
86776             // Save existing generator state
86777             var statements = [];
86778             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86779             var savedInStatementContainingYield = inStatementContainingYield;
86780             var savedBlocks = blocks;
86781             var savedBlockOffsets = blockOffsets;
86782             var savedBlockActions = blockActions;
86783             var savedBlockStack = blockStack;
86784             var savedLabelOffsets = labelOffsets;
86785             var savedLabelExpressions = labelExpressions;
86786             var savedNextLabelId = nextLabelId;
86787             var savedOperations = operations;
86788             var savedOperationArguments = operationArguments;
86789             var savedOperationLocations = operationLocations;
86790             var savedState = state;
86791             // Initialize generator state
86792             inGeneratorFunctionBody = true;
86793             inStatementContainingYield = false;
86794             blocks = undefined;
86795             blockOffsets = undefined;
86796             blockActions = undefined;
86797             blockStack = undefined;
86798             labelOffsets = undefined;
86799             labelExpressions = undefined;
86800             nextLabelId = 1;
86801             operations = undefined;
86802             operationArguments = undefined;
86803             operationLocations = undefined;
86804             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86805             // Build the generator
86806             resumeLexicalEnvironment();
86807             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86808             transformAndEmitStatements(body.statements, statementOffset);
86809             var buildResult = build();
86810             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86811             statements.push(ts.createReturn(buildResult));
86812             // Restore previous generator state
86813             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86814             inStatementContainingYield = savedInStatementContainingYield;
86815             blocks = savedBlocks;
86816             blockOffsets = savedBlockOffsets;
86817             blockActions = savedBlockActions;
86818             blockStack = savedBlockStack;
86819             labelOffsets = savedLabelOffsets;
86820             labelExpressions = savedLabelExpressions;
86821             nextLabelId = savedNextLabelId;
86822             operations = savedOperations;
86823             operationArguments = savedOperationArguments;
86824             operationLocations = savedOperationLocations;
86825             state = savedState;
86826             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
86827         }
86828         /**
86829          * Visits a variable statement.
86830          *
86831          * This will be called when one of the following conditions are met:
86832          * - The variable statement is contained within the body of a generator function.
86833          *
86834          * @param node The node to visit.
86835          */
86836         function visitVariableStatement(node) {
86837             if (node.transformFlags & 262144 /* ContainsYield */) {
86838                 transformAndEmitVariableDeclarationList(node.declarationList);
86839                 return undefined;
86840             }
86841             else {
86842                 // Do not hoist custom prologues.
86843                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
86844                     return node;
86845                 }
86846                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
86847                     var variable = _a[_i];
86848                     hoistVariableDeclaration(variable.name);
86849                 }
86850                 var variables = ts.getInitializedVariables(node.declarationList);
86851                 if (variables.length === 0) {
86852                     return undefined;
86853                 }
86854                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
86855             }
86856         }
86857         /**
86858          * Visits a binary expression.
86859          *
86860          * This will be called when one of the following conditions are met:
86861          * - The node contains a YieldExpression.
86862          *
86863          * @param node The node to visit.
86864          */
86865         function visitBinaryExpression(node) {
86866             var assoc = ts.getExpressionAssociativity(node);
86867             switch (assoc) {
86868                 case 0 /* Left */:
86869                     return visitLeftAssociativeBinaryExpression(node);
86870                 case 1 /* Right */:
86871                     return visitRightAssociativeBinaryExpression(node);
86872                 default:
86873                     return ts.Debug.assertNever(assoc);
86874             }
86875         }
86876         /**
86877          * Visits a right-associative binary expression containing `yield`.
86878          *
86879          * @param node The node to visit.
86880          */
86881         function visitRightAssociativeBinaryExpression(node) {
86882             var left = node.left, right = node.right;
86883             if (containsYield(right)) {
86884                 var target = void 0;
86885                 switch (left.kind) {
86886                     case 194 /* PropertyAccessExpression */:
86887                         // [source]
86888                         //      a.b = yield;
86889                         //
86890                         // [intermediate]
86891                         //  .local _a
86892                         //      _a = a;
86893                         //  .yield resumeLabel
86894                         //  .mark resumeLabel
86895                         //      _a.b = %sent%;
86896                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
86897                         break;
86898                     case 195 /* ElementAccessExpression */:
86899                         // [source]
86900                         //      a[b] = yield;
86901                         //
86902                         // [intermediate]
86903                         //  .local _a, _b
86904                         //      _a = a;
86905                         //      _b = b;
86906                         //  .yield resumeLabel
86907                         //  .mark resumeLabel
86908                         //      _a[_b] = %sent%;
86909                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
86910                         break;
86911                     default:
86912                         target = ts.visitNode(left, visitor, ts.isExpression);
86913                         break;
86914                 }
86915                 var operator = node.operatorToken.kind;
86916                 if (ts.isCompoundAssignment(operator)) {
86917                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
86918                 }
86919                 else {
86920                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
86921                 }
86922             }
86923             return ts.visitEachChild(node, visitor, context);
86924         }
86925         function visitLeftAssociativeBinaryExpression(node) {
86926             if (containsYield(node.right)) {
86927                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
86928                     return visitLogicalBinaryExpression(node);
86929                 }
86930                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
86931                     return visitCommaExpression(node);
86932                 }
86933                 // [source]
86934                 //      a() + (yield) + c()
86935                 //
86936                 // [intermediate]
86937                 //  .local _a
86938                 //      _a = a();
86939                 //  .yield resumeLabel
86940                 //      _a + %sent% + c()
86941                 var clone_6 = ts.getMutableClone(node);
86942                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
86943                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
86944                 return clone_6;
86945             }
86946             return ts.visitEachChild(node, visitor, context);
86947         }
86948         /**
86949          * Visits a logical binary expression containing `yield`.
86950          *
86951          * @param node A node to visit.
86952          */
86953         function visitLogicalBinaryExpression(node) {
86954             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
86955             // to be transformed as such:
86956             //
86957             // [source]
86958             //      x = a() && yield;
86959             //
86960             // [intermediate]
86961             //  .local _a
86962             //      _a = a();
86963             //  .brfalse resultLabel, (_a)
86964             //  .yield resumeLabel
86965             //  .mark resumeLabel
86966             //      _a = %sent%;
86967             //  .mark resultLabel
86968             //      x = _a;
86969             //
86970             // [source]
86971             //      x = a() || yield;
86972             //
86973             // [intermediate]
86974             //  .local _a
86975             //      _a = a();
86976             //  .brtrue resultLabel, (_a)
86977             //  .yield resumeLabel
86978             //  .mark resumeLabel
86979             //      _a = %sent%;
86980             //  .mark resultLabel
86981             //      x = _a;
86982             var resultLabel = defineLabel();
86983             var resultLocal = declareLocal();
86984             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
86985             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
86986                 // Logical `&&` shortcuts when the left-hand operand is falsey.
86987                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
86988             }
86989             else {
86990                 // Logical `||` shortcuts when the left-hand operand is truthy.
86991                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
86992             }
86993             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
86994             markLabel(resultLabel);
86995             return resultLocal;
86996         }
86997         /**
86998          * Visits a comma expression containing `yield`.
86999          *
87000          * @param node The node to visit.
87001          */
87002         function visitCommaExpression(node) {
87003             // [source]
87004             //      x = a(), yield, b();
87005             //
87006             // [intermediate]
87007             //      a();
87008             //  .yield resumeLabel
87009             //  .mark resumeLabel
87010             //      x = %sent%, b();
87011             var pendingExpressions = [];
87012             visit(node.left);
87013             visit(node.right);
87014             return ts.inlineExpressions(pendingExpressions);
87015             function visit(node) {
87016                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87017                     visit(node.left);
87018                     visit(node.right);
87019                 }
87020                 else {
87021                     if (containsYield(node) && pendingExpressions.length > 0) {
87022                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87023                         pendingExpressions = [];
87024                     }
87025                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87026                 }
87027             }
87028         }
87029         /**
87030          * Visits a conditional expression containing `yield`.
87031          *
87032          * @param node The node to visit.
87033          */
87034         function visitConditionalExpression(node) {
87035             // [source]
87036             //      x = a() ? yield : b();
87037             //
87038             // [intermediate]
87039             //  .local _a
87040             //  .brfalse whenFalseLabel, (a())
87041             //  .yield resumeLabel
87042             //  .mark resumeLabel
87043             //      _a = %sent%;
87044             //  .br resultLabel
87045             //  .mark whenFalseLabel
87046             //      _a = b();
87047             //  .mark resultLabel
87048             //      x = _a;
87049             // We only need to perform a specific transformation if a `yield` expression exists
87050             // in either the `whenTrue` or `whenFalse` branches.
87051             // A `yield` in the condition will be handled by the normal visitor.
87052             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87053                 var whenFalseLabel = defineLabel();
87054                 var resultLabel = defineLabel();
87055                 var resultLocal = declareLocal();
87056                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87057                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87058                 emitBreak(resultLabel);
87059                 markLabel(whenFalseLabel);
87060                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87061                 markLabel(resultLabel);
87062                 return resultLocal;
87063             }
87064             return ts.visitEachChild(node, visitor, context);
87065         }
87066         /**
87067          * Visits a `yield` expression.
87068          *
87069          * @param node The node to visit.
87070          */
87071         function visitYieldExpression(node) {
87072             // [source]
87073             //      x = yield a();
87074             //
87075             // [intermediate]
87076             //  .yield resumeLabel, (a())
87077             //  .mark resumeLabel
87078             //      x = %sent%;
87079             var resumeLabel = defineLabel();
87080             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87081             if (node.asteriskToken) {
87082                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87083                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87084                     : expression;
87085                 emitYieldStar(iterator, /*location*/ node);
87086             }
87087             else {
87088                 emitYield(expression, /*location*/ node);
87089             }
87090             markLabel(resumeLabel);
87091             return createGeneratorResume(/*location*/ node);
87092         }
87093         /**
87094          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87095          *
87096          * @param node The node to visit.
87097          */
87098         function visitArrayLiteralExpression(node) {
87099             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87100         }
87101         /**
87102          * Visits an array of expressions containing one or more YieldExpression nodes
87103          * and returns an expression for the resulting value.
87104          *
87105          * @param elements The elements to visit.
87106          * @param multiLine Whether array literals created should be emitted on multiple lines.
87107          */
87108         function visitElements(elements, leadingElement, location, multiLine) {
87109             // [source]
87110             //      ar = [1, yield, 2];
87111             //
87112             // [intermediate]
87113             //  .local _a
87114             //      _a = [1];
87115             //  .yield resumeLabel
87116             //  .mark resumeLabel
87117             //      ar = _a.concat([%sent%, 2]);
87118             var numInitialElements = countInitialNodesWithoutYield(elements);
87119             var temp;
87120             if (numInitialElements > 0) {
87121                 temp = declareLocal();
87122                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87123                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87124                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87125                 leadingElement = undefined;
87126             }
87127             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87128             return temp
87129                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87130                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87131             function reduceElement(expressions, element) {
87132                 if (containsYield(element) && expressions.length > 0) {
87133                     var hasAssignedTemp = temp !== undefined;
87134                     if (!temp) {
87135                         temp = declareLocal();
87136                     }
87137                     emitAssignment(temp, hasAssignedTemp
87138                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87139                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87140                     leadingElement = undefined;
87141                     expressions = [];
87142                 }
87143                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87144                 return expressions;
87145             }
87146         }
87147         function visitObjectLiteralExpression(node) {
87148             // [source]
87149             //      o = {
87150             //          a: 1,
87151             //          b: yield,
87152             //          c: 2
87153             //      };
87154             //
87155             // [intermediate]
87156             //  .local _a
87157             //      _a = {
87158             //          a: 1
87159             //      };
87160             //  .yield resumeLabel
87161             //  .mark resumeLabel
87162             //      o = (_a.b = %sent%,
87163             //          _a.c = 2,
87164             //          _a);
87165             var properties = node.properties;
87166             var multiLine = node.multiLine;
87167             var numInitialProperties = countInitialNodesWithoutYield(properties);
87168             var temp = declareLocal();
87169             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87170             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87171             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87172             return ts.inlineExpressions(expressions);
87173             function reduceProperty(expressions, property) {
87174                 if (containsYield(property) && expressions.length > 0) {
87175                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87176                     expressions = [];
87177                 }
87178                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87179                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87180                 if (visited) {
87181                     if (multiLine) {
87182                         ts.startOnNewLine(visited);
87183                     }
87184                     expressions.push(visited);
87185                 }
87186                 return expressions;
87187             }
87188         }
87189         /**
87190          * Visits an ElementAccessExpression that contains a YieldExpression.
87191          *
87192          * @param node The node to visit.
87193          */
87194         function visitElementAccessExpression(node) {
87195             if (containsYield(node.argumentExpression)) {
87196                 // [source]
87197                 //      a = x[yield];
87198                 //
87199                 // [intermediate]
87200                 //  .local _a
87201                 //      _a = x;
87202                 //  .yield resumeLabel
87203                 //  .mark resumeLabel
87204                 //      a = _a[%sent%]
87205                 var clone_7 = ts.getMutableClone(node);
87206                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87207                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87208                 return clone_7;
87209             }
87210             return ts.visitEachChild(node, visitor, context);
87211         }
87212         function visitCallExpression(node) {
87213             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87214                 // [source]
87215                 //      a.b(1, yield, 2);
87216                 //
87217                 // [intermediate]
87218                 //  .local _a, _b, _c
87219                 //      _b = (_a = a).b;
87220                 //      _c = [1];
87221                 //  .yield resumeLabel
87222                 //  .mark resumeLabel
87223                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87224                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87225                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87226                 /*location*/ node), node);
87227             }
87228             return ts.visitEachChild(node, visitor, context);
87229         }
87230         function visitNewExpression(node) {
87231             if (ts.forEach(node.arguments, containsYield)) {
87232                 // [source]
87233                 //      new a.b(1, yield, 2);
87234                 //
87235                 // [intermediate]
87236                 //  .local _a, _b, _c
87237                 //      _b = (_a = a.b).bind;
87238                 //      _c = [1];
87239                 //  .yield resumeLabel
87240                 //  .mark resumeLabel
87241                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87242                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87243                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87244                 /*leadingElement*/ ts.createVoidZero())), 
87245                 /*typeArguments*/ undefined, []), node), node);
87246             }
87247             return ts.visitEachChild(node, visitor, context);
87248         }
87249         function transformAndEmitStatements(statements, start) {
87250             if (start === void 0) { start = 0; }
87251             var numStatements = statements.length;
87252             for (var i = start; i < numStatements; i++) {
87253                 transformAndEmitStatement(statements[i]);
87254             }
87255         }
87256         function transformAndEmitEmbeddedStatement(node) {
87257             if (ts.isBlock(node)) {
87258                 transformAndEmitStatements(node.statements);
87259             }
87260             else {
87261                 transformAndEmitStatement(node);
87262             }
87263         }
87264         function transformAndEmitStatement(node) {
87265             var savedInStatementContainingYield = inStatementContainingYield;
87266             if (!inStatementContainingYield) {
87267                 inStatementContainingYield = containsYield(node);
87268             }
87269             transformAndEmitStatementWorker(node);
87270             inStatementContainingYield = savedInStatementContainingYield;
87271         }
87272         function transformAndEmitStatementWorker(node) {
87273             switch (node.kind) {
87274                 case 223 /* Block */:
87275                     return transformAndEmitBlock(node);
87276                 case 226 /* ExpressionStatement */:
87277                     return transformAndEmitExpressionStatement(node);
87278                 case 227 /* IfStatement */:
87279                     return transformAndEmitIfStatement(node);
87280                 case 228 /* DoStatement */:
87281                     return transformAndEmitDoStatement(node);
87282                 case 229 /* WhileStatement */:
87283                     return transformAndEmitWhileStatement(node);
87284                 case 230 /* ForStatement */:
87285                     return transformAndEmitForStatement(node);
87286                 case 231 /* ForInStatement */:
87287                     return transformAndEmitForInStatement(node);
87288                 case 233 /* ContinueStatement */:
87289                     return transformAndEmitContinueStatement(node);
87290                 case 234 /* BreakStatement */:
87291                     return transformAndEmitBreakStatement(node);
87292                 case 235 /* ReturnStatement */:
87293                     return transformAndEmitReturnStatement(node);
87294                 case 236 /* WithStatement */:
87295                     return transformAndEmitWithStatement(node);
87296                 case 237 /* SwitchStatement */:
87297                     return transformAndEmitSwitchStatement(node);
87298                 case 238 /* LabeledStatement */:
87299                     return transformAndEmitLabeledStatement(node);
87300                 case 239 /* ThrowStatement */:
87301                     return transformAndEmitThrowStatement(node);
87302                 case 240 /* TryStatement */:
87303                     return transformAndEmitTryStatement(node);
87304                 default:
87305                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87306             }
87307         }
87308         function transformAndEmitBlock(node) {
87309             if (containsYield(node)) {
87310                 transformAndEmitStatements(node.statements);
87311             }
87312             else {
87313                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87314             }
87315         }
87316         function transformAndEmitExpressionStatement(node) {
87317             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87318         }
87319         function transformAndEmitVariableDeclarationList(node) {
87320             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87321                 var variable = _a[_i];
87322                 var name = ts.getSynthesizedClone(variable.name);
87323                 ts.setCommentRange(name, variable.name);
87324                 hoistVariableDeclaration(name);
87325             }
87326             var variables = ts.getInitializedVariables(node);
87327             var numVariables = variables.length;
87328             var variablesWritten = 0;
87329             var pendingExpressions = [];
87330             while (variablesWritten < numVariables) {
87331                 for (var i = variablesWritten; i < numVariables; i++) {
87332                     var variable = variables[i];
87333                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87334                         break;
87335                     }
87336                     pendingExpressions.push(transformInitializedVariable(variable));
87337                 }
87338                 if (pendingExpressions.length) {
87339                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87340                     variablesWritten += pendingExpressions.length;
87341                     pendingExpressions = [];
87342                 }
87343             }
87344             return undefined;
87345         }
87346         function transformInitializedVariable(node) {
87347             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87348         }
87349         function transformAndEmitIfStatement(node) {
87350             if (containsYield(node)) {
87351                 // [source]
87352                 //      if (x)
87353                 //          /*thenStatement*/
87354                 //      else
87355                 //          /*elseStatement*/
87356                 //
87357                 // [intermediate]
87358                 //  .brfalse elseLabel, (x)
87359                 //      /*thenStatement*/
87360                 //  .br endLabel
87361                 //  .mark elseLabel
87362                 //      /*elseStatement*/
87363                 //  .mark endLabel
87364                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87365                     var endLabel = defineLabel();
87366                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87367                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87368                     transformAndEmitEmbeddedStatement(node.thenStatement);
87369                     if (node.elseStatement) {
87370                         emitBreak(endLabel);
87371                         markLabel(elseLabel);
87372                         transformAndEmitEmbeddedStatement(node.elseStatement);
87373                     }
87374                     markLabel(endLabel);
87375                 }
87376                 else {
87377                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87378                 }
87379             }
87380             else {
87381                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87382             }
87383         }
87384         function transformAndEmitDoStatement(node) {
87385             if (containsYield(node)) {
87386                 // [source]
87387                 //      do {
87388                 //          /*body*/
87389                 //      }
87390                 //      while (i < 10);
87391                 //
87392                 // [intermediate]
87393                 //  .loop conditionLabel, endLabel
87394                 //  .mark loopLabel
87395                 //      /*body*/
87396                 //  .mark conditionLabel
87397                 //  .brtrue loopLabel, (i < 10)
87398                 //  .endloop
87399                 //  .mark endLabel
87400                 var conditionLabel = defineLabel();
87401                 var loopLabel = defineLabel();
87402                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87403                 markLabel(loopLabel);
87404                 transformAndEmitEmbeddedStatement(node.statement);
87405                 markLabel(conditionLabel);
87406                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87407                 endLoopBlock();
87408             }
87409             else {
87410                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87411             }
87412         }
87413         function visitDoStatement(node) {
87414             if (inStatementContainingYield) {
87415                 beginScriptLoopBlock();
87416                 node = ts.visitEachChild(node, visitor, context);
87417                 endLoopBlock();
87418                 return node;
87419             }
87420             else {
87421                 return ts.visitEachChild(node, visitor, context);
87422             }
87423         }
87424         function transformAndEmitWhileStatement(node) {
87425             if (containsYield(node)) {
87426                 // [source]
87427                 //      while (i < 10) {
87428                 //          /*body*/
87429                 //      }
87430                 //
87431                 // [intermediate]
87432                 //  .loop loopLabel, endLabel
87433                 //  .mark loopLabel
87434                 //  .brfalse endLabel, (i < 10)
87435                 //      /*body*/
87436                 //  .br loopLabel
87437                 //  .endloop
87438                 //  .mark endLabel
87439                 var loopLabel = defineLabel();
87440                 var endLabel = beginLoopBlock(loopLabel);
87441                 markLabel(loopLabel);
87442                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87443                 transformAndEmitEmbeddedStatement(node.statement);
87444                 emitBreak(loopLabel);
87445                 endLoopBlock();
87446             }
87447             else {
87448                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87449             }
87450         }
87451         function visitWhileStatement(node) {
87452             if (inStatementContainingYield) {
87453                 beginScriptLoopBlock();
87454                 node = ts.visitEachChild(node, visitor, context);
87455                 endLoopBlock();
87456                 return node;
87457             }
87458             else {
87459                 return ts.visitEachChild(node, visitor, context);
87460             }
87461         }
87462         function transformAndEmitForStatement(node) {
87463             if (containsYield(node)) {
87464                 // [source]
87465                 //      for (var i = 0; i < 10; i++) {
87466                 //          /*body*/
87467                 //      }
87468                 //
87469                 // [intermediate]
87470                 //  .local i
87471                 //      i = 0;
87472                 //  .loop incrementLabel, endLoopLabel
87473                 //  .mark conditionLabel
87474                 //  .brfalse endLoopLabel, (i < 10)
87475                 //      /*body*/
87476                 //  .mark incrementLabel
87477                 //      i++;
87478                 //  .br conditionLabel
87479                 //  .endloop
87480                 //  .mark endLoopLabel
87481                 var conditionLabel = defineLabel();
87482                 var incrementLabel = defineLabel();
87483                 var endLabel = beginLoopBlock(incrementLabel);
87484                 if (node.initializer) {
87485                     var initializer = node.initializer;
87486                     if (ts.isVariableDeclarationList(initializer)) {
87487                         transformAndEmitVariableDeclarationList(initializer);
87488                     }
87489                     else {
87490                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87491                     }
87492                 }
87493                 markLabel(conditionLabel);
87494                 if (node.condition) {
87495                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87496                 }
87497                 transformAndEmitEmbeddedStatement(node.statement);
87498                 markLabel(incrementLabel);
87499                 if (node.incrementor) {
87500                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87501                 }
87502                 emitBreak(conditionLabel);
87503                 endLoopBlock();
87504             }
87505             else {
87506                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87507             }
87508         }
87509         function visitForStatement(node) {
87510             if (inStatementContainingYield) {
87511                 beginScriptLoopBlock();
87512             }
87513             var initializer = node.initializer;
87514             if (initializer && ts.isVariableDeclarationList(initializer)) {
87515                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87516                     var variable = _a[_i];
87517                     hoistVariableDeclaration(variable.name);
87518                 }
87519                 var variables = ts.getInitializedVariables(initializer);
87520                 node = ts.updateFor(node, variables.length > 0
87521                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87522                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87523             }
87524             else {
87525                 node = ts.visitEachChild(node, visitor, context);
87526             }
87527             if (inStatementContainingYield) {
87528                 endLoopBlock();
87529             }
87530             return node;
87531         }
87532         function transformAndEmitForInStatement(node) {
87533             // TODO(rbuckton): Source map locations
87534             if (containsYield(node)) {
87535                 // [source]
87536                 //      for (var p in o) {
87537                 //          /*body*/
87538                 //      }
87539                 //
87540                 // [intermediate]
87541                 //  .local _a, _b, _i
87542                 //      _a = [];
87543                 //      for (_b in o) _a.push(_b);
87544                 //      _i = 0;
87545                 //  .loop incrementLabel, endLoopLabel
87546                 //  .mark conditionLabel
87547                 //  .brfalse endLoopLabel, (_i < _a.length)
87548                 //      p = _a[_i];
87549                 //      /*body*/
87550                 //  .mark incrementLabel
87551                 //      _b++;
87552                 //  .br conditionLabel
87553                 //  .endloop
87554                 //  .mark endLoopLabel
87555                 var keysArray = declareLocal(); // _a
87556                 var key = declareLocal(); // _b
87557                 var keysIndex = ts.createLoopVariable(); // _i
87558                 var initializer = node.initializer;
87559                 hoistVariableDeclaration(keysIndex);
87560                 emitAssignment(keysArray, ts.createArrayLiteral());
87561                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87562                 /*typeArguments*/ undefined, [key]))));
87563                 emitAssignment(keysIndex, ts.createLiteral(0));
87564                 var conditionLabel = defineLabel();
87565                 var incrementLabel = defineLabel();
87566                 var endLabel = beginLoopBlock(incrementLabel);
87567                 markLabel(conditionLabel);
87568                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87569                 var variable = void 0;
87570                 if (ts.isVariableDeclarationList(initializer)) {
87571                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87572                         var variable_1 = _a[_i];
87573                         hoistVariableDeclaration(variable_1.name);
87574                     }
87575                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87576                 }
87577                 else {
87578                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87579                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87580                 }
87581                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87582                 transformAndEmitEmbeddedStatement(node.statement);
87583                 markLabel(incrementLabel);
87584                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87585                 emitBreak(conditionLabel);
87586                 endLoopBlock();
87587             }
87588             else {
87589                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87590             }
87591         }
87592         function visitForInStatement(node) {
87593             // [source]
87594             //      for (var x in a) {
87595             //          /*body*/
87596             //      }
87597             //
87598             // [intermediate]
87599             //  .local x
87600             //  .loop
87601             //      for (x in a) {
87602             //          /*body*/
87603             //      }
87604             //  .endloop
87605             if (inStatementContainingYield) {
87606                 beginScriptLoopBlock();
87607             }
87608             var initializer = node.initializer;
87609             if (ts.isVariableDeclarationList(initializer)) {
87610                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87611                     var variable = _a[_i];
87612                     hoistVariableDeclaration(variable.name);
87613                 }
87614                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87615             }
87616             else {
87617                 node = ts.visitEachChild(node, visitor, context);
87618             }
87619             if (inStatementContainingYield) {
87620                 endLoopBlock();
87621             }
87622             return node;
87623         }
87624         function transformAndEmitContinueStatement(node) {
87625             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87626             if (label > 0) {
87627                 emitBreak(label, /*location*/ node);
87628             }
87629             else {
87630                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87631                 emitStatement(node);
87632             }
87633         }
87634         function visitContinueStatement(node) {
87635             if (inStatementContainingYield) {
87636                 var label = findContinueTarget(node.label && ts.idText(node.label));
87637                 if (label > 0) {
87638                     return createInlineBreak(label, /*location*/ node);
87639                 }
87640             }
87641             return ts.visitEachChild(node, visitor, context);
87642         }
87643         function transformAndEmitBreakStatement(node) {
87644             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87645             if (label > 0) {
87646                 emitBreak(label, /*location*/ node);
87647             }
87648             else {
87649                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87650                 emitStatement(node);
87651             }
87652         }
87653         function visitBreakStatement(node) {
87654             if (inStatementContainingYield) {
87655                 var label = findBreakTarget(node.label && ts.idText(node.label));
87656                 if (label > 0) {
87657                     return createInlineBreak(label, /*location*/ node);
87658                 }
87659             }
87660             return ts.visitEachChild(node, visitor, context);
87661         }
87662         function transformAndEmitReturnStatement(node) {
87663             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87664             /*location*/ node);
87665         }
87666         function visitReturnStatement(node) {
87667             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87668             /*location*/ node);
87669         }
87670         function transformAndEmitWithStatement(node) {
87671             if (containsYield(node)) {
87672                 // [source]
87673                 //      with (x) {
87674                 //          /*body*/
87675                 //      }
87676                 //
87677                 // [intermediate]
87678                 //  .with (x)
87679                 //      /*body*/
87680                 //  .endwith
87681                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87682                 transformAndEmitEmbeddedStatement(node.statement);
87683                 endWithBlock();
87684             }
87685             else {
87686                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87687             }
87688         }
87689         function transformAndEmitSwitchStatement(node) {
87690             if (containsYield(node.caseBlock)) {
87691                 // [source]
87692                 //      switch (x) {
87693                 //          case a:
87694                 //              /*caseStatements*/
87695                 //          case b:
87696                 //              /*caseStatements*/
87697                 //          default:
87698                 //              /*defaultStatements*/
87699                 //      }
87700                 //
87701                 // [intermediate]
87702                 //  .local _a
87703                 //  .switch endLabel
87704                 //      _a = x;
87705                 //      switch (_a) {
87706                 //          case a:
87707                 //  .br clauseLabels[0]
87708                 //      }
87709                 //      switch (_a) {
87710                 //          case b:
87711                 //  .br clauseLabels[1]
87712                 //      }
87713                 //  .br clauseLabels[2]
87714                 //  .mark clauseLabels[0]
87715                 //      /*caseStatements*/
87716                 //  .mark clauseLabels[1]
87717                 //      /*caseStatements*/
87718                 //  .mark clauseLabels[2]
87719                 //      /*caseStatements*/
87720                 //  .endswitch
87721                 //  .mark endLabel
87722                 var caseBlock = node.caseBlock;
87723                 var numClauses = caseBlock.clauses.length;
87724                 var endLabel = beginSwitchBlock();
87725                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87726                 // Create labels for each clause and find the index of the first default clause.
87727                 var clauseLabels = [];
87728                 var defaultClauseIndex = -1;
87729                 for (var i = 0; i < numClauses; i++) {
87730                     var clause = caseBlock.clauses[i];
87731                     clauseLabels.push(defineLabel());
87732                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87733                         defaultClauseIndex = i;
87734                     }
87735                 }
87736                 // Emit switch statements for each run of case clauses either from the first case
87737                 // clause or the next case clause with a `yield` in its expression, up to the next
87738                 // case clause with a `yield` in its expression.
87739                 var clausesWritten = 0;
87740                 var pendingClauses = [];
87741                 while (clausesWritten < numClauses) {
87742                     var defaultClausesSkipped = 0;
87743                     for (var i = clausesWritten; i < numClauses; i++) {
87744                         var clause = caseBlock.clauses[i];
87745                         if (clause.kind === 277 /* CaseClause */) {
87746                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87747                                 break;
87748                             }
87749                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87750                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87751                             ]));
87752                         }
87753                         else {
87754                             defaultClausesSkipped++;
87755                         }
87756                     }
87757                     if (pendingClauses.length) {
87758                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87759                         clausesWritten += pendingClauses.length;
87760                         pendingClauses = [];
87761                     }
87762                     if (defaultClausesSkipped > 0) {
87763                         clausesWritten += defaultClausesSkipped;
87764                         defaultClausesSkipped = 0;
87765                     }
87766                 }
87767                 if (defaultClauseIndex >= 0) {
87768                     emitBreak(clauseLabels[defaultClauseIndex]);
87769                 }
87770                 else {
87771                     emitBreak(endLabel);
87772                 }
87773                 for (var i = 0; i < numClauses; i++) {
87774                     markLabel(clauseLabels[i]);
87775                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87776                 }
87777                 endSwitchBlock();
87778             }
87779             else {
87780                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87781             }
87782         }
87783         function visitSwitchStatement(node) {
87784             if (inStatementContainingYield) {
87785                 beginScriptSwitchBlock();
87786             }
87787             node = ts.visitEachChild(node, visitor, context);
87788             if (inStatementContainingYield) {
87789                 endSwitchBlock();
87790             }
87791             return node;
87792         }
87793         function transformAndEmitLabeledStatement(node) {
87794             if (containsYield(node)) {
87795                 // [source]
87796                 //      x: {
87797                 //          /*body*/
87798                 //      }
87799                 //
87800                 // [intermediate]
87801                 //  .labeled "x", endLabel
87802                 //      /*body*/
87803                 //  .endlabeled
87804                 //  .mark endLabel
87805                 beginLabeledBlock(ts.idText(node.label));
87806                 transformAndEmitEmbeddedStatement(node.statement);
87807                 endLabeledBlock();
87808             }
87809             else {
87810                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87811             }
87812         }
87813         function visitLabeledStatement(node) {
87814             if (inStatementContainingYield) {
87815                 beginScriptLabeledBlock(ts.idText(node.label));
87816             }
87817             node = ts.visitEachChild(node, visitor, context);
87818             if (inStatementContainingYield) {
87819                 endLabeledBlock();
87820             }
87821             return node;
87822         }
87823         function transformAndEmitThrowStatement(node) {
87824             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
87825             /*location*/ node);
87826         }
87827         function transformAndEmitTryStatement(node) {
87828             if (containsYield(node)) {
87829                 // [source]
87830                 //      try {
87831                 //          /*tryBlock*/
87832                 //      }
87833                 //      catch (e) {
87834                 //          /*catchBlock*/
87835                 //      }
87836                 //      finally {
87837                 //          /*finallyBlock*/
87838                 //      }
87839                 //
87840                 // [intermediate]
87841                 //  .local _a
87842                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
87843                 //  .mark tryLabel
87844                 //  .nop
87845                 //      /*tryBlock*/
87846                 //  .br endLabel
87847                 //  .catch
87848                 //  .mark catchLabel
87849                 //      _a = %error%;
87850                 //      /*catchBlock*/
87851                 //  .br endLabel
87852                 //  .finally
87853                 //  .mark finallyLabel
87854                 //      /*finallyBlock*/
87855                 //  .endfinally
87856                 //  .endtry
87857                 //  .mark endLabel
87858                 beginExceptionBlock();
87859                 transformAndEmitEmbeddedStatement(node.tryBlock);
87860                 if (node.catchClause) {
87861                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
87862                     transformAndEmitEmbeddedStatement(node.catchClause.block);
87863                 }
87864                 if (node.finallyBlock) {
87865                     beginFinallyBlock();
87866                     transformAndEmitEmbeddedStatement(node.finallyBlock);
87867                 }
87868                 endExceptionBlock();
87869             }
87870             else {
87871                 emitStatement(ts.visitEachChild(node, visitor, context));
87872             }
87873         }
87874         function containsYield(node) {
87875             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
87876         }
87877         function countInitialNodesWithoutYield(nodes) {
87878             var numNodes = nodes.length;
87879             for (var i = 0; i < numNodes; i++) {
87880                 if (containsYield(nodes[i])) {
87881                     return i;
87882                 }
87883             }
87884             return -1;
87885         }
87886         function onSubstituteNode(hint, node) {
87887             node = previousOnSubstituteNode(hint, node);
87888             if (hint === 1 /* Expression */) {
87889                 return substituteExpression(node);
87890             }
87891             return node;
87892         }
87893         function substituteExpression(node) {
87894             if (ts.isIdentifier(node)) {
87895                 return substituteExpressionIdentifier(node);
87896             }
87897             return node;
87898         }
87899         function substituteExpressionIdentifier(node) {
87900             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
87901                 var original = ts.getOriginalNode(node);
87902                 if (ts.isIdentifier(original) && original.parent) {
87903                     var declaration = resolver.getReferencedValueDeclaration(original);
87904                     if (declaration) {
87905                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
87906                         if (name) {
87907                             var clone_8 = ts.getMutableClone(name);
87908                             ts.setSourceMapRange(clone_8, node);
87909                             ts.setCommentRange(clone_8, node);
87910                             return clone_8;
87911                         }
87912                     }
87913                 }
87914             }
87915             return node;
87916         }
87917         function cacheExpression(node) {
87918             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
87919                 return node;
87920             }
87921             var temp = ts.createTempVariable(hoistVariableDeclaration);
87922             emitAssignment(temp, node, /*location*/ node);
87923             return temp;
87924         }
87925         function declareLocal(name) {
87926             var temp = name
87927                 ? ts.createUniqueName(name)
87928                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
87929             hoistVariableDeclaration(temp);
87930             return temp;
87931         }
87932         /**
87933          * Defines a label, uses as the target of a Break operation.
87934          */
87935         function defineLabel() {
87936             if (!labelOffsets) {
87937                 labelOffsets = [];
87938             }
87939             var label = nextLabelId;
87940             nextLabelId++;
87941             labelOffsets[label] = -1;
87942             return label;
87943         }
87944         /**
87945          * Marks the current operation with the specified label.
87946          */
87947         function markLabel(label) {
87948             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
87949             labelOffsets[label] = operations ? operations.length : 0;
87950         }
87951         /**
87952          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
87953          *
87954          * @param block Information about the block.
87955          */
87956         function beginBlock(block) {
87957             if (!blocks) {
87958                 blocks = [];
87959                 blockActions = [];
87960                 blockOffsets = [];
87961                 blockStack = [];
87962             }
87963             var index = blockActions.length;
87964             blockActions[index] = 0 /* Open */;
87965             blockOffsets[index] = operations ? operations.length : 0;
87966             blocks[index] = block;
87967             blockStack.push(block);
87968             return index;
87969         }
87970         /**
87971          * Ends the current block operation.
87972          */
87973         function endBlock() {
87974             var block = peekBlock();
87975             if (block === undefined)
87976                 return ts.Debug.fail("beginBlock was never called.");
87977             var index = blockActions.length;
87978             blockActions[index] = 1 /* Close */;
87979             blockOffsets[index] = operations ? operations.length : 0;
87980             blocks[index] = block;
87981             blockStack.pop();
87982             return block;
87983         }
87984         /**
87985          * Gets the current open block.
87986          */
87987         function peekBlock() {
87988             return ts.lastOrUndefined(blockStack);
87989         }
87990         /**
87991          * Gets the kind of the current open block.
87992          */
87993         function peekBlockKind() {
87994             var block = peekBlock();
87995             return block && block.kind;
87996         }
87997         /**
87998          * Begins a code block for a generated `with` statement.
87999          *
88000          * @param expression An identifier representing expression for the `with` block.
88001          */
88002         function beginWithBlock(expression) {
88003             var startLabel = defineLabel();
88004             var endLabel = defineLabel();
88005             markLabel(startLabel);
88006             beginBlock({
88007                 kind: 1 /* With */,
88008                 expression: expression,
88009                 startLabel: startLabel,
88010                 endLabel: endLabel
88011             });
88012         }
88013         /**
88014          * Ends a code block for a generated `with` statement.
88015          */
88016         function endWithBlock() {
88017             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88018             var block = endBlock();
88019             markLabel(block.endLabel);
88020         }
88021         /**
88022          * Begins a code block for a generated `try` statement.
88023          */
88024         function beginExceptionBlock() {
88025             var startLabel = defineLabel();
88026             var endLabel = defineLabel();
88027             markLabel(startLabel);
88028             beginBlock({
88029                 kind: 0 /* Exception */,
88030                 state: 0 /* Try */,
88031                 startLabel: startLabel,
88032                 endLabel: endLabel
88033             });
88034             emitNop();
88035             return endLabel;
88036         }
88037         /**
88038          * Enters the `catch` clause of a generated `try` statement.
88039          *
88040          * @param variable The catch variable.
88041          */
88042         function beginCatchBlock(variable) {
88043             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88044             // generated identifiers should already be unique within a file
88045             var name;
88046             if (ts.isGeneratedIdentifier(variable.name)) {
88047                 name = variable.name;
88048                 hoistVariableDeclaration(variable.name);
88049             }
88050             else {
88051                 var text = ts.idText(variable.name);
88052                 name = declareLocal(text);
88053                 if (!renamedCatchVariables) {
88054                     renamedCatchVariables = ts.createMap();
88055                     renamedCatchVariableDeclarations = [];
88056                     context.enableSubstitution(75 /* Identifier */);
88057                 }
88058                 renamedCatchVariables.set(text, true);
88059                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88060             }
88061             var exception = peekBlock();
88062             ts.Debug.assert(exception.state < 1 /* Catch */);
88063             var endLabel = exception.endLabel;
88064             emitBreak(endLabel);
88065             var catchLabel = defineLabel();
88066             markLabel(catchLabel);
88067             exception.state = 1 /* Catch */;
88068             exception.catchVariable = name;
88069             exception.catchLabel = catchLabel;
88070             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88071             emitNop();
88072         }
88073         /**
88074          * Enters the `finally` block of a generated `try` statement.
88075          */
88076         function beginFinallyBlock() {
88077             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88078             var exception = peekBlock();
88079             ts.Debug.assert(exception.state < 2 /* Finally */);
88080             var endLabel = exception.endLabel;
88081             emitBreak(endLabel);
88082             var finallyLabel = defineLabel();
88083             markLabel(finallyLabel);
88084             exception.state = 2 /* Finally */;
88085             exception.finallyLabel = finallyLabel;
88086         }
88087         /**
88088          * Ends the code block for a generated `try` statement.
88089          */
88090         function endExceptionBlock() {
88091             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88092             var exception = endBlock();
88093             var state = exception.state;
88094             if (state < 2 /* Finally */) {
88095                 emitBreak(exception.endLabel);
88096             }
88097             else {
88098                 emitEndfinally();
88099             }
88100             markLabel(exception.endLabel);
88101             emitNop();
88102             exception.state = 3 /* Done */;
88103         }
88104         /**
88105          * Begins a code block that supports `break` or `continue` statements that are defined in
88106          * the source tree and not from generated code.
88107          *
88108          * @param labelText Names from containing labeled statements.
88109          */
88110         function beginScriptLoopBlock() {
88111             beginBlock({
88112                 kind: 3 /* Loop */,
88113                 isScript: true,
88114                 breakLabel: -1,
88115                 continueLabel: -1
88116             });
88117         }
88118         /**
88119          * Begins a code block that supports `break` or `continue` statements that are defined in
88120          * generated code. Returns a label used to mark the operation to which to jump when a
88121          * `break` statement targets this block.
88122          *
88123          * @param continueLabel A Label used to mark the operation to which to jump when a
88124          *                      `continue` statement targets this block.
88125          */
88126         function beginLoopBlock(continueLabel) {
88127             var breakLabel = defineLabel();
88128             beginBlock({
88129                 kind: 3 /* Loop */,
88130                 isScript: false,
88131                 breakLabel: breakLabel,
88132                 continueLabel: continueLabel,
88133             });
88134             return breakLabel;
88135         }
88136         /**
88137          * Ends a code block that supports `break` or `continue` statements that are defined in
88138          * generated code or in the source tree.
88139          */
88140         function endLoopBlock() {
88141             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88142             var block = endBlock();
88143             var breakLabel = block.breakLabel;
88144             if (!block.isScript) {
88145                 markLabel(breakLabel);
88146             }
88147         }
88148         /**
88149          * Begins a code block that supports `break` statements that are defined in the source
88150          * tree and not from generated code.
88151          *
88152          */
88153         function beginScriptSwitchBlock() {
88154             beginBlock({
88155                 kind: 2 /* Switch */,
88156                 isScript: true,
88157                 breakLabel: -1
88158             });
88159         }
88160         /**
88161          * Begins a code block that supports `break` statements that are defined in generated code.
88162          * Returns a label used to mark the operation to which to jump when a `break` statement
88163          * targets this block.
88164          */
88165         function beginSwitchBlock() {
88166             var breakLabel = defineLabel();
88167             beginBlock({
88168                 kind: 2 /* Switch */,
88169                 isScript: false,
88170                 breakLabel: breakLabel,
88171             });
88172             return breakLabel;
88173         }
88174         /**
88175          * Ends a code block that supports `break` statements that are defined in generated code.
88176          */
88177         function endSwitchBlock() {
88178             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88179             var block = endBlock();
88180             var breakLabel = block.breakLabel;
88181             if (!block.isScript) {
88182                 markLabel(breakLabel);
88183             }
88184         }
88185         function beginScriptLabeledBlock(labelText) {
88186             beginBlock({
88187                 kind: 4 /* Labeled */,
88188                 isScript: true,
88189                 labelText: labelText,
88190                 breakLabel: -1
88191             });
88192         }
88193         function beginLabeledBlock(labelText) {
88194             var breakLabel = defineLabel();
88195             beginBlock({
88196                 kind: 4 /* Labeled */,
88197                 isScript: false,
88198                 labelText: labelText,
88199                 breakLabel: breakLabel
88200             });
88201         }
88202         function endLabeledBlock() {
88203             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88204             var block = endBlock();
88205             if (!block.isScript) {
88206                 markLabel(block.breakLabel);
88207             }
88208         }
88209         /**
88210          * Indicates whether the provided block supports `break` statements.
88211          *
88212          * @param block A code block.
88213          */
88214         function supportsUnlabeledBreak(block) {
88215             return block.kind === 2 /* Switch */
88216                 || block.kind === 3 /* Loop */;
88217         }
88218         /**
88219          * Indicates whether the provided block supports `break` statements with labels.
88220          *
88221          * @param block A code block.
88222          */
88223         function supportsLabeledBreakOrContinue(block) {
88224             return block.kind === 4 /* Labeled */;
88225         }
88226         /**
88227          * Indicates whether the provided block supports `continue` statements.
88228          *
88229          * @param block A code block.
88230          */
88231         function supportsUnlabeledContinue(block) {
88232             return block.kind === 3 /* Loop */;
88233         }
88234         function hasImmediateContainingLabeledBlock(labelText, start) {
88235             for (var j = start; j >= 0; j--) {
88236                 var containingBlock = blockStack[j];
88237                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88238                     if (containingBlock.labelText === labelText) {
88239                         return true;
88240                     }
88241                 }
88242                 else {
88243                     break;
88244                 }
88245             }
88246             return false;
88247         }
88248         /**
88249          * Finds the label that is the target for a `break` statement.
88250          *
88251          * @param labelText An optional name of a containing labeled statement.
88252          */
88253         function findBreakTarget(labelText) {
88254             if (blockStack) {
88255                 if (labelText) {
88256                     for (var i = blockStack.length - 1; i >= 0; i--) {
88257                         var block = blockStack[i];
88258                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88259                             return block.breakLabel;
88260                         }
88261                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88262                             return block.breakLabel;
88263                         }
88264                     }
88265                 }
88266                 else {
88267                     for (var i = blockStack.length - 1; i >= 0; i--) {
88268                         var block = blockStack[i];
88269                         if (supportsUnlabeledBreak(block)) {
88270                             return block.breakLabel;
88271                         }
88272                     }
88273                 }
88274             }
88275             return 0;
88276         }
88277         /**
88278          * Finds the label that is the target for a `continue` statement.
88279          *
88280          * @param labelText An optional name of a containing labeled statement.
88281          */
88282         function findContinueTarget(labelText) {
88283             if (blockStack) {
88284                 if (labelText) {
88285                     for (var i = blockStack.length - 1; i >= 0; i--) {
88286                         var block = blockStack[i];
88287                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88288                             return block.continueLabel;
88289                         }
88290                     }
88291                 }
88292                 else {
88293                     for (var i = blockStack.length - 1; i >= 0; i--) {
88294                         var block = blockStack[i];
88295                         if (supportsUnlabeledContinue(block)) {
88296                             return block.continueLabel;
88297                         }
88298                     }
88299                 }
88300             }
88301             return 0;
88302         }
88303         /**
88304          * Creates an expression that can be used to indicate the value for a label.
88305          *
88306          * @param label A label.
88307          */
88308         function createLabel(label) {
88309             if (label !== undefined && label > 0) {
88310                 if (labelExpressions === undefined) {
88311                     labelExpressions = [];
88312                 }
88313                 var expression = ts.createLiteral(-1);
88314                 if (labelExpressions[label] === undefined) {
88315                     labelExpressions[label] = [expression];
88316                 }
88317                 else {
88318                     labelExpressions[label].push(expression);
88319                 }
88320                 return expression;
88321             }
88322             return ts.createOmittedExpression();
88323         }
88324         /**
88325          * Creates a numeric literal for the provided instruction.
88326          */
88327         function createInstruction(instruction) {
88328             var literal = ts.createLiteral(instruction);
88329             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88330             return literal;
88331         }
88332         /**
88333          * Creates a statement that can be used indicate a Break operation to the provided label.
88334          *
88335          * @param label A label.
88336          * @param location An optional source map location for the statement.
88337          */
88338         function createInlineBreak(label, location) {
88339             ts.Debug.assertLessThan(0, label, "Invalid label");
88340             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88341                 createInstruction(3 /* Break */),
88342                 createLabel(label)
88343             ])), location);
88344         }
88345         /**
88346          * Creates a statement that can be used indicate a Return operation.
88347          *
88348          * @param expression The expression for the return statement.
88349          * @param location An optional source map location for the statement.
88350          */
88351         function createInlineReturn(expression, location) {
88352             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88353                 ? [createInstruction(2 /* Return */), expression]
88354                 : [createInstruction(2 /* Return */)])), location);
88355         }
88356         /**
88357          * Creates an expression that can be used to resume from a Yield operation.
88358          */
88359         function createGeneratorResume(location) {
88360             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88361             /*typeArguments*/ undefined, []), location);
88362         }
88363         /**
88364          * Emits an empty instruction.
88365          */
88366         function emitNop() {
88367             emitWorker(0 /* Nop */);
88368         }
88369         /**
88370          * Emits a Statement.
88371          *
88372          * @param node A statement.
88373          */
88374         function emitStatement(node) {
88375             if (node) {
88376                 emitWorker(1 /* Statement */, [node]);
88377             }
88378             else {
88379                 emitNop();
88380             }
88381         }
88382         /**
88383          * Emits an Assignment operation.
88384          *
88385          * @param left The left-hand side of the assignment.
88386          * @param right The right-hand side of the assignment.
88387          * @param location An optional source map location for the assignment.
88388          */
88389         function emitAssignment(left, right, location) {
88390             emitWorker(2 /* Assign */, [left, right], location);
88391         }
88392         /**
88393          * Emits a Break operation to the specified label.
88394          *
88395          * @param label A label.
88396          * @param location An optional source map location for the assignment.
88397          */
88398         function emitBreak(label, location) {
88399             emitWorker(3 /* Break */, [label], location);
88400         }
88401         /**
88402          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88403          * value at runtime.
88404          *
88405          * @param label A label.
88406          * @param condition The condition.
88407          * @param location An optional source map location for the assignment.
88408          */
88409         function emitBreakWhenTrue(label, condition, location) {
88410             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88411         }
88412         /**
88413          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88414          * runtime.
88415          *
88416          * @param label A label.
88417          * @param condition The condition.
88418          * @param location An optional source map location for the assignment.
88419          */
88420         function emitBreakWhenFalse(label, condition, location) {
88421             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88422         }
88423         /**
88424          * Emits a YieldStar operation for the provided expression.
88425          *
88426          * @param expression An optional value for the yield operation.
88427          * @param location An optional source map location for the assignment.
88428          */
88429         function emitYieldStar(expression, location) {
88430             emitWorker(7 /* YieldStar */, [expression], location);
88431         }
88432         /**
88433          * Emits a Yield operation for the provided expression.
88434          *
88435          * @param expression An optional value for the yield operation.
88436          * @param location An optional source map location for the assignment.
88437          */
88438         function emitYield(expression, location) {
88439             emitWorker(6 /* Yield */, [expression], location);
88440         }
88441         /**
88442          * Emits a Return operation for the provided expression.
88443          *
88444          * @param expression An optional value for the operation.
88445          * @param location An optional source map location for the assignment.
88446          */
88447         function emitReturn(expression, location) {
88448             emitWorker(8 /* Return */, [expression], location);
88449         }
88450         /**
88451          * Emits a Throw operation for the provided expression.
88452          *
88453          * @param expression A value for the operation.
88454          * @param location An optional source map location for the assignment.
88455          */
88456         function emitThrow(expression, location) {
88457             emitWorker(9 /* Throw */, [expression], location);
88458         }
88459         /**
88460          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88461          */
88462         function emitEndfinally() {
88463             emitWorker(10 /* Endfinally */);
88464         }
88465         /**
88466          * Emits an operation.
88467          *
88468          * @param code The OpCode for the operation.
88469          * @param args The optional arguments for the operation.
88470          */
88471         function emitWorker(code, args, location) {
88472             if (operations === undefined) {
88473                 operations = [];
88474                 operationArguments = [];
88475                 operationLocations = [];
88476             }
88477             if (labelOffsets === undefined) {
88478                 // mark entry point
88479                 markLabel(defineLabel());
88480             }
88481             var operationIndex = operations.length;
88482             operations[operationIndex] = code;
88483             operationArguments[operationIndex] = args;
88484             operationLocations[operationIndex] = location;
88485         }
88486         /**
88487          * Builds the generator function body.
88488          */
88489         function build() {
88490             blockIndex = 0;
88491             labelNumber = 0;
88492             labelNumbers = undefined;
88493             lastOperationWasAbrupt = false;
88494             lastOperationWasCompletion = false;
88495             clauses = undefined;
88496             statements = undefined;
88497             exceptionBlockStack = undefined;
88498             currentExceptionBlock = undefined;
88499             withBlockStack = undefined;
88500             var buildResult = buildStatements();
88501             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88502             /*modifiers*/ undefined, 
88503             /*asteriskToken*/ undefined, 
88504             /*name*/ undefined, 
88505             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88506             /*type*/ undefined, ts.createBlock(buildResult, 
88507             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88508         }
88509         /**
88510          * Builds the statements for the generator function body.
88511          */
88512         function buildStatements() {
88513             if (operations) {
88514                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88515                     writeOperation(operationIndex);
88516                 }
88517                 flushFinalLabel(operations.length);
88518             }
88519             else {
88520                 flushFinalLabel(0);
88521             }
88522             if (clauses) {
88523                 var labelExpression = ts.createPropertyAccess(state, "label");
88524                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88525                 return [ts.startOnNewLine(switchStatement)];
88526             }
88527             if (statements) {
88528                 return statements;
88529             }
88530             return [];
88531         }
88532         /**
88533          * Flush the current label and advance to a new label.
88534          */
88535         function flushLabel() {
88536             if (!statements) {
88537                 return;
88538             }
88539             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88540             lastOperationWasAbrupt = false;
88541             lastOperationWasCompletion = false;
88542             labelNumber++;
88543         }
88544         /**
88545          * Flush the final label of the generator function body.
88546          */
88547         function flushFinalLabel(operationIndex) {
88548             if (isFinalLabelReachable(operationIndex)) {
88549                 tryEnterLabel(operationIndex);
88550                 withBlockStack = undefined;
88551                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88552             }
88553             if (statements && clauses) {
88554                 appendLabel(/*markLabelEnd*/ false);
88555             }
88556             updateLabelExpressions();
88557         }
88558         /**
88559          * Tests whether the final label of the generator function body
88560          * is reachable by user code.
88561          */
88562         function isFinalLabelReachable(operationIndex) {
88563             // if the last operation was *not* a completion (return/throw) then
88564             // the final label is reachable.
88565             if (!lastOperationWasCompletion) {
88566                 return true;
88567             }
88568             // if there are no labels defined or referenced, then the final label is
88569             // not reachable.
88570             if (!labelOffsets || !labelExpressions) {
88571                 return false;
88572             }
88573             // if the label for this offset is referenced, then the final label
88574             // is reachable.
88575             for (var label = 0; label < labelOffsets.length; label++) {
88576                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88577                     return true;
88578                 }
88579             }
88580             return false;
88581         }
88582         /**
88583          * Appends a case clause for the last label and sets the new label.
88584          *
88585          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88586          *                     from a previous case clause and the change in labels should be
88587          *                     reflected on the `state` object.
88588          */
88589         function appendLabel(markLabelEnd) {
88590             if (!clauses) {
88591                 clauses = [];
88592             }
88593             if (statements) {
88594                 if (withBlockStack) {
88595                     // The previous label was nested inside one or more `with` blocks, so we
88596                     // surround the statements in generated `with` blocks to create the same environment.
88597                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88598                         var withBlock = withBlockStack[i];
88599                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88600                     }
88601                 }
88602                 if (currentExceptionBlock) {
88603                     // The previous label was nested inside of an exception block, so we must
88604                     // indicate entry into a protected region by pushing the label numbers
88605                     // for each block in the protected region.
88606                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88607                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88608                     /*typeArguments*/ undefined, [
88609                         ts.createArrayLiteral([
88610                             createLabel(startLabel),
88611                             createLabel(catchLabel),
88612                             createLabel(finallyLabel),
88613                             createLabel(endLabel)
88614                         ])
88615                     ])));
88616                     currentExceptionBlock = undefined;
88617                 }
88618                 if (markLabelEnd) {
88619                     // The case clause for the last label falls through to this label, so we
88620                     // add an assignment statement to reflect the change in labels.
88621                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88622                 }
88623             }
88624             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88625             statements = undefined;
88626         }
88627         /**
88628          * Tries to enter into a new label at the current operation index.
88629          */
88630         function tryEnterLabel(operationIndex) {
88631             if (!labelOffsets) {
88632                 return;
88633             }
88634             for (var label = 0; label < labelOffsets.length; label++) {
88635                 if (labelOffsets[label] === operationIndex) {
88636                     flushLabel();
88637                     if (labelNumbers === undefined) {
88638                         labelNumbers = [];
88639                     }
88640                     if (labelNumbers[labelNumber] === undefined) {
88641                         labelNumbers[labelNumber] = [label];
88642                     }
88643                     else {
88644                         labelNumbers[labelNumber].push(label);
88645                     }
88646                 }
88647             }
88648         }
88649         /**
88650          * Updates literal expressions for labels with actual label numbers.
88651          */
88652         function updateLabelExpressions() {
88653             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88654                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88655                     var labels = labelNumbers[labelNumber_1];
88656                     if (labels !== undefined) {
88657                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88658                             var label = labels_1[_i];
88659                             var expressions = labelExpressions[label];
88660                             if (expressions !== undefined) {
88661                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88662                                     var expression = expressions_1[_a];
88663                                     expression.text = String(labelNumber_1);
88664                                 }
88665                             }
88666                         }
88667                     }
88668                 }
88669             }
88670         }
88671         /**
88672          * Tries to enter or leave a code block.
88673          */
88674         function tryEnterOrLeaveBlock(operationIndex) {
88675             if (blocks) {
88676                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88677                     var block = blocks[blockIndex];
88678                     var blockAction = blockActions[blockIndex];
88679                     switch (block.kind) {
88680                         case 0 /* Exception */:
88681                             if (blockAction === 0 /* Open */) {
88682                                 if (!exceptionBlockStack) {
88683                                     exceptionBlockStack = [];
88684                                 }
88685                                 if (!statements) {
88686                                     statements = [];
88687                                 }
88688                                 exceptionBlockStack.push(currentExceptionBlock);
88689                                 currentExceptionBlock = block;
88690                             }
88691                             else if (blockAction === 1 /* Close */) {
88692                                 currentExceptionBlock = exceptionBlockStack.pop();
88693                             }
88694                             break;
88695                         case 1 /* With */:
88696                             if (blockAction === 0 /* Open */) {
88697                                 if (!withBlockStack) {
88698                                     withBlockStack = [];
88699                                 }
88700                                 withBlockStack.push(block);
88701                             }
88702                             else if (blockAction === 1 /* Close */) {
88703                                 withBlockStack.pop();
88704                             }
88705                             break;
88706                         // default: do nothing
88707                     }
88708                 }
88709             }
88710         }
88711         /**
88712          * Writes an operation as a statement to the current label's statement list.
88713          *
88714          * @param operation The OpCode of the operation
88715          */
88716         function writeOperation(operationIndex) {
88717             tryEnterLabel(operationIndex);
88718             tryEnterOrLeaveBlock(operationIndex);
88719             // early termination, nothing else to process in this label
88720             if (lastOperationWasAbrupt) {
88721                 return;
88722             }
88723             lastOperationWasAbrupt = false;
88724             lastOperationWasCompletion = false;
88725             var opcode = operations[operationIndex];
88726             if (opcode === 0 /* Nop */) {
88727                 return;
88728             }
88729             else if (opcode === 10 /* Endfinally */) {
88730                 return writeEndfinally();
88731             }
88732             var args = operationArguments[operationIndex];
88733             if (opcode === 1 /* Statement */) {
88734                 return writeStatement(args[0]);
88735             }
88736             var location = operationLocations[operationIndex];
88737             switch (opcode) {
88738                 case 2 /* Assign */:
88739                     return writeAssign(args[0], args[1], location);
88740                 case 3 /* Break */:
88741                     return writeBreak(args[0], location);
88742                 case 4 /* BreakWhenTrue */:
88743                     return writeBreakWhenTrue(args[0], args[1], location);
88744                 case 5 /* BreakWhenFalse */:
88745                     return writeBreakWhenFalse(args[0], args[1], location);
88746                 case 6 /* Yield */:
88747                     return writeYield(args[0], location);
88748                 case 7 /* YieldStar */:
88749                     return writeYieldStar(args[0], location);
88750                 case 8 /* Return */:
88751                     return writeReturn(args[0], location);
88752                 case 9 /* Throw */:
88753                     return writeThrow(args[0], location);
88754             }
88755         }
88756         /**
88757          * Writes a statement to the current label's statement list.
88758          *
88759          * @param statement A statement to write.
88760          */
88761         function writeStatement(statement) {
88762             if (statement) {
88763                 if (!statements) {
88764                     statements = [statement];
88765                 }
88766                 else {
88767                     statements.push(statement);
88768                 }
88769             }
88770         }
88771         /**
88772          * Writes an Assign operation to the current label's statement list.
88773          *
88774          * @param left The left-hand side of the assignment.
88775          * @param right The right-hand side of the assignment.
88776          * @param operationLocation The source map location for the operation.
88777          */
88778         function writeAssign(left, right, operationLocation) {
88779             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88780         }
88781         /**
88782          * Writes a Throw operation to the current label's statement list.
88783          *
88784          * @param expression The value to throw.
88785          * @param operationLocation The source map location for the operation.
88786          */
88787         function writeThrow(expression, operationLocation) {
88788             lastOperationWasAbrupt = true;
88789             lastOperationWasCompletion = true;
88790             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88791         }
88792         /**
88793          * Writes a Return operation to the current label's statement list.
88794          *
88795          * @param expression The value to return.
88796          * @param operationLocation The source map location for the operation.
88797          */
88798         function writeReturn(expression, operationLocation) {
88799             lastOperationWasAbrupt = true;
88800             lastOperationWasCompletion = true;
88801             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88802                 ? [createInstruction(2 /* Return */), expression]
88803                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88804         }
88805         /**
88806          * Writes a Break operation to the current label's statement list.
88807          *
88808          * @param label The label for the Break.
88809          * @param operationLocation The source map location for the operation.
88810          */
88811         function writeBreak(label, operationLocation) {
88812             lastOperationWasAbrupt = true;
88813             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88814                 createInstruction(3 /* Break */),
88815                 createLabel(label)
88816             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88817         }
88818         /**
88819          * Writes a BreakWhenTrue operation to the current label's statement list.
88820          *
88821          * @param label The label for the Break.
88822          * @param condition The condition for the Break.
88823          * @param operationLocation The source map location for the operation.
88824          */
88825         function writeBreakWhenTrue(label, condition, operationLocation) {
88826             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88827                 createInstruction(3 /* Break */),
88828                 createLabel(label)
88829             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88830         }
88831         /**
88832          * Writes a BreakWhenFalse operation to the current label's statement list.
88833          *
88834          * @param label The label for the Break.
88835          * @param condition The condition for the Break.
88836          * @param operationLocation The source map location for the operation.
88837          */
88838         function writeBreakWhenFalse(label, condition, operationLocation) {
88839             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88840                 createInstruction(3 /* Break */),
88841                 createLabel(label)
88842             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88843         }
88844         /**
88845          * Writes a Yield operation to the current label's statement list.
88846          *
88847          * @param expression The expression to yield.
88848          * @param operationLocation The source map location for the operation.
88849          */
88850         function writeYield(expression, operationLocation) {
88851             lastOperationWasAbrupt = true;
88852             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88853                 ? [createInstruction(4 /* Yield */), expression]
88854                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88855         }
88856         /**
88857          * Writes a YieldStar instruction to the current label's statement list.
88858          *
88859          * @param expression The expression to yield.
88860          * @param operationLocation The source map location for the operation.
88861          */
88862         function writeYieldStar(expression, operationLocation) {
88863             lastOperationWasAbrupt = true;
88864             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88865                 createInstruction(5 /* YieldStar */),
88866                 expression
88867             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88868         }
88869         /**
88870          * Writes an Endfinally instruction to the current label's statement list.
88871          */
88872         function writeEndfinally() {
88873             lastOperationWasAbrupt = true;
88874             writeStatement(ts.createReturn(ts.createArrayLiteral([
88875                 createInstruction(7 /* Endfinally */)
88876             ])));
88877         }
88878     }
88879     ts.transformGenerators = transformGenerators;
88880     function createGeneratorHelper(context, body) {
88881         context.requestEmitHelper(ts.generatorHelper);
88882         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
88883         /*typeArguments*/ undefined, [ts.createThis(), body]);
88884     }
88885     // The __generator helper is used by down-level transformations to emulate the runtime
88886     // semantics of an ES2015 generator function. When called, this helper returns an
88887     // object that implements the Iterator protocol, in that it has `next`, `return`, and
88888     // `throw` methods that step through the generator when invoked.
88889     //
88890     // parameters:
88891     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
88892     //  @param body     A function that acts as the transformed generator body.
88893     //
88894     // variables:
88895     //  _       Persistent state for the generator that is shared between the helper and the
88896     //          generator body. The state object has the following members:
88897     //            sent() - A method that returns or throws the current completion value.
88898     //            label  - The next point at which to resume evaluation of the generator body.
88899     //            trys   - A stack of protected regions (try/catch/finally blocks).
88900     //            ops    - A stack of pending instructions when inside of a finally block.
88901     //  f       A value indicating whether the generator is executing.
88902     //  y       An iterator to delegate for a yield*.
88903     //  t       A temporary variable that holds one of the following values (note that these
88904     //          cases do not overlap):
88905     //          - The completion value when resuming from a `yield` or `yield*`.
88906     //          - The error value for a catch block.
88907     //          - The current protected region (array of try/catch/finally/end labels).
88908     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
88909     //            of a `yield*`.
88910     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
88911     //
88912     // functions:
88913     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
88914     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
88915     //              completed.
88916     //
88917     // The __generator helper understands a limited set of instructions:
88918     //  0: next(value?)     - Start or resume the generator with the specified value.
88919     //  1: throw(error)     - Resume the generator with an exception. If the generator is
88920     //                        suspended inside of one or more protected regions, evaluates
88921     //                        any intervening finally blocks between the current label and
88922     //                        the nearest catch block or function boundary. If uncaught, the
88923     //                        exception is thrown to the caller.
88924     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
88925     //                        suspended inside of one or more protected regions, evaluates any
88926     //                        intervening finally blocks.
88927     //  3: break(label)     - Jump to the specified label. If the label is outside of the
88928     //                        current protected region, evaluates any intervening finally
88929     //                        blocks.
88930     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
88931     //                        resumed, the generator will continue at the next label.
88932     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
88933     //                        delegation completes, the generator will continue at the next
88934     //                        label.
88935     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
88936     //                        the current label is inside of one or more protected regions,
88937     //                        evaluates any intervening finally blocks between the current
88938     //                        label and the nearest catch block or function boundary. If
88939     //                        uncaught, the exception is thrown to the caller.
88940     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
88941     //                        entering a finally block.
88942     //
88943     // For examples of how these are used, see the comments in ./transformers/generators.ts
88944     ts.generatorHelper = {
88945         name: "typescript:generator",
88946         importName: "__generator",
88947         scoped: false,
88948         priority: 6,
88949         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            };"
88950     };
88951 })(ts || (ts = {}));
88952 /*@internal*/
88953 var ts;
88954 (function (ts) {
88955     function transformModule(context) {
88956         function getTransformModuleDelegate(moduleKind) {
88957             switch (moduleKind) {
88958                 case ts.ModuleKind.AMD: return transformAMDModule;
88959                 case ts.ModuleKind.UMD: return transformUMDModule;
88960                 default: return transformCommonJSModule;
88961             }
88962         }
88963         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88964         var compilerOptions = context.getCompilerOptions();
88965         var resolver = context.getEmitResolver();
88966         var host = context.getEmitHost();
88967         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
88968         var moduleKind = ts.getEmitModuleKind(compilerOptions);
88969         var previousOnSubstituteNode = context.onSubstituteNode;
88970         var previousOnEmitNode = context.onEmitNode;
88971         context.onSubstituteNode = onSubstituteNode;
88972         context.onEmitNode = onEmitNode;
88973         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
88974         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
88975         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
88976         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
88977         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
88978         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
88979         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
88980         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
88981         var currentSourceFile; // The current file.
88982         var currentModuleInfo; // The ExternalModuleInfo for the current file.
88983         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
88984         var needUMDDynamicImportHelper;
88985         return ts.chainBundle(transformSourceFile);
88986         /**
88987          * Transforms the module aspects of a SourceFile.
88988          *
88989          * @param node The SourceFile node.
88990          */
88991         function transformSourceFile(node) {
88992             if (node.isDeclarationFile ||
88993                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
88994                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
88995                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
88996                 return node;
88997             }
88998             currentSourceFile = node;
88999             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89000             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89001             // Perform the transformation.
89002             var transformModule = getTransformModuleDelegate(moduleKind);
89003             var updated = transformModule(node);
89004             currentSourceFile = undefined;
89005             currentModuleInfo = undefined;
89006             needUMDDynamicImportHelper = false;
89007             return ts.aggregateTransformFlags(updated);
89008         }
89009         function shouldEmitUnderscoreUnderscoreESModule() {
89010             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89011                 return true;
89012             }
89013             return false;
89014         }
89015         /**
89016          * Transforms a SourceFile into a CommonJS module.
89017          *
89018          * @param node The SourceFile node.
89019          */
89020         function transformCommonJSModule(node) {
89021             startLexicalEnvironment();
89022             var statements = [];
89023             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89024             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89025             if (shouldEmitUnderscoreUnderscoreESModule()) {
89026                 ts.append(statements, createUnderscoreUnderscoreESModule());
89027             }
89028             if (ts.length(currentModuleInfo.exportedNames)) {
89029                 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())));
89030             }
89031             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89032             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89033             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89034             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89035             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89036             ts.addEmitHelpers(updated, context.readEmitHelpers());
89037             return updated;
89038         }
89039         /**
89040          * Transforms a SourceFile into an AMD module.
89041          *
89042          * @param node The SourceFile node.
89043          */
89044         function transformAMDModule(node) {
89045             var define = ts.createIdentifier("define");
89046             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89047             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89048             // An AMD define function has the following shape:
89049             //
89050             //     define(id?, dependencies?, factory);
89051             //
89052             // This has the shape of the following:
89053             //
89054             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89055             //
89056             // The location of the alias in the parameter list in the factory function needs to
89057             // match the position of the module name in the dependency list.
89058             //
89059             // To ensure this is true in cases of modules with no aliases, e.g.:
89060             //
89061             //     import "module"
89062             //
89063             // or
89064             //
89065             //     /// <amd-dependency path= "a.css" />
89066             //
89067             // we need to add modules without alias names to the end of the dependencies list
89068             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89069             // Create an updated SourceFile:
89070             //
89071             //     define(moduleName?, ["module1", "module2"], function ...
89072             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89073                 ts.createExpressionStatement(ts.createCall(define, 
89074                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89075                     // Add the dependency array argument:
89076                     //
89077                     //     ["require", "exports", module1", "module2", ...]
89078                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89079                         ts.createLiteral("require"),
89080                         ts.createLiteral("exports")
89081                     ], aliasedModuleNames, unaliasedModuleNames)),
89082                     // Add the module body function argument:
89083                     //
89084                     //     function (require, exports, module1, module2) ...
89085                     jsonSourceFile ?
89086                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89087                         ts.createFunctionExpression(
89088                         /*modifiers*/ undefined, 
89089                         /*asteriskToken*/ undefined, 
89090                         /*name*/ undefined, 
89091                         /*typeParameters*/ undefined, __spreadArrays([
89092                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89093                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89094                         ], importAliasNames), 
89095                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89096                 ])))
89097             ]), 
89098             /*location*/ node.statements));
89099             ts.addEmitHelpers(updated, context.readEmitHelpers());
89100             return updated;
89101         }
89102         /**
89103          * Transforms a SourceFile into a UMD module.
89104          *
89105          * @param node The SourceFile node.
89106          */
89107         function transformUMDModule(node) {
89108             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89109             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89110             var umdHeader = ts.createFunctionExpression(
89111             /*modifiers*/ undefined, 
89112             /*asteriskToken*/ undefined, 
89113             /*name*/ undefined, 
89114             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89115             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89116                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89117                     ts.createVariableStatement(
89118                     /*modifiers*/ undefined, [
89119                         ts.createVariableDeclaration("v", 
89120                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89121                         /*typeArguments*/ undefined, [
89122                             ts.createIdentifier("require"),
89123                             ts.createIdentifier("exports")
89124                         ]))
89125                     ]),
89126                     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 */)
89127                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89128                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89129                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89130                         ts.createArrayLiteral(__spreadArrays([
89131                             ts.createLiteral("require"),
89132                             ts.createLiteral("exports")
89133                         ], aliasedModuleNames, unaliasedModuleNames)),
89134                         ts.createIdentifier("factory")
89135                     ])))
89136                 ])))
89137             ], 
89138             /*multiLine*/ true), 
89139             /*location*/ undefined));
89140             // Create an updated SourceFile:
89141             //
89142             //  (function (factory) {
89143             //      if (typeof module === "object" && typeof module.exports === "object") {
89144             //          var v = factory(require, exports);
89145             //          if (v !== undefined) module.exports = v;
89146             //      }
89147             //      else if (typeof define === 'function' && define.amd) {
89148             //          define(["require", "exports"], factory);
89149             //      }
89150             //  })(function ...)
89151             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89152                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89153                 /*typeArguments*/ undefined, [
89154                     // Add the module body function argument:
89155                     //
89156                     //     function (require, exports) ...
89157                     ts.createFunctionExpression(
89158                     /*modifiers*/ undefined, 
89159                     /*asteriskToken*/ undefined, 
89160                     /*name*/ undefined, 
89161                     /*typeParameters*/ undefined, __spreadArrays([
89162                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89163                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89164                     ], importAliasNames), 
89165                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89166                 ]))
89167             ]), 
89168             /*location*/ node.statements));
89169             ts.addEmitHelpers(updated, context.readEmitHelpers());
89170             return updated;
89171         }
89172         /**
89173          * Collect the additional asynchronous dependencies for the module.
89174          *
89175          * @param node The source file.
89176          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89177          */
89178         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89179             // names of modules with corresponding parameter in the factory function
89180             var aliasedModuleNames = [];
89181             // names of modules with no corresponding parameters in factory function
89182             var unaliasedModuleNames = [];
89183             // names of the parameters in the factory function; these
89184             // parameters need to match the indexes of the corresponding
89185             // module names in aliasedModuleNames.
89186             var importAliasNames = [];
89187             // Fill in amd-dependency tags
89188             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89189                 var amdDependency = _a[_i];
89190                 if (amdDependency.name) {
89191                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89192                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89193                 }
89194                 else {
89195                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89196                 }
89197             }
89198             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89199                 var importNode = _c[_b];
89200                 // Find the name of the external module
89201                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89202                 // Find the name of the module alias, if there is one
89203                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89204                 // It is possible that externalModuleName is undefined if it is not string literal.
89205                 // This can happen in the invalid import syntax.
89206                 // E.g : "import * from alias from 'someLib';"
89207                 if (externalModuleName) {
89208                     if (includeNonAmdDependencies && importAliasName) {
89209                         // Set emitFlags on the name of the classDeclaration
89210                         // This is so that when printer will not substitute the identifier
89211                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89212                         aliasedModuleNames.push(externalModuleName);
89213                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89214                     }
89215                     else {
89216                         unaliasedModuleNames.push(externalModuleName);
89217                     }
89218                 }
89219             }
89220             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89221         }
89222         function getAMDImportExpressionForImport(node) {
89223             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89224                 return undefined;
89225             }
89226             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89227             var expr = getHelperExpressionForImport(node, name);
89228             if (expr === name) {
89229                 return undefined;
89230             }
89231             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89232         }
89233         /**
89234          * Transforms a SourceFile into an AMD or UMD module body.
89235          *
89236          * @param node The SourceFile node.
89237          */
89238         function transformAsynchronousModuleBody(node) {
89239             startLexicalEnvironment();
89240             var statements = [];
89241             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89242             if (shouldEmitUnderscoreUnderscoreESModule()) {
89243                 ts.append(statements, createUnderscoreUnderscoreESModule());
89244             }
89245             if (ts.length(currentModuleInfo.exportedNames)) {
89246                 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())));
89247             }
89248             // Visit each statement of the module body.
89249             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89250             if (moduleKind === ts.ModuleKind.AMD) {
89251                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89252             }
89253             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89254             // Append the 'export =' statement if provided.
89255             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89256             // End the lexical environment for the module body
89257             // and merge any new lexical declarations.
89258             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89259             var body = ts.createBlock(statements, /*multiLine*/ true);
89260             if (needUMDDynamicImportHelper) {
89261                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89262             }
89263             return body;
89264         }
89265         /**
89266          * Adds the down-level representation of `export=` to the statement list if one exists
89267          * in the source file.
89268          *
89269          * @param statements The Statement list to modify.
89270          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89271          * return statement.
89272          */
89273         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89274             if (currentModuleInfo.exportEquals) {
89275                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89276                 if (expressionResult) {
89277                     if (emitAsReturn) {
89278                         var statement = ts.createReturn(expressionResult);
89279                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89280                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89281                         statements.push(statement);
89282                     }
89283                     else {
89284                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89285                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89286                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89287                         statements.push(statement);
89288                     }
89289                 }
89290             }
89291         }
89292         //
89293         // Top-Level Source Element Visitors
89294         //
89295         /**
89296          * Visits a node at the top level of the source file.
89297          *
89298          * @param node The node to visit.
89299          */
89300         function sourceElementVisitor(node) {
89301             switch (node.kind) {
89302                 case 254 /* ImportDeclaration */:
89303                     return visitImportDeclaration(node);
89304                 case 253 /* ImportEqualsDeclaration */:
89305                     return visitImportEqualsDeclaration(node);
89306                 case 260 /* ExportDeclaration */:
89307                     return visitExportDeclaration(node);
89308                 case 259 /* ExportAssignment */:
89309                     return visitExportAssignment(node);
89310                 case 225 /* VariableStatement */:
89311                     return visitVariableStatement(node);
89312                 case 244 /* FunctionDeclaration */:
89313                     return visitFunctionDeclaration(node);
89314                 case 245 /* ClassDeclaration */:
89315                     return visitClassDeclaration(node);
89316                 case 328 /* MergeDeclarationMarker */:
89317                     return visitMergeDeclarationMarker(node);
89318                 case 329 /* EndOfDeclarationMarker */:
89319                     return visitEndOfDeclarationMarker(node);
89320                 default:
89321                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89322             }
89323         }
89324         function moduleExpressionElementVisitor(node) {
89325             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89326             // as export/import statements are only transformed at the top level of a file.
89327             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89328                 return node;
89329             }
89330             if (ts.isImportCall(node)) {
89331                 return visitImportCallExpression(node);
89332             }
89333             else if (ts.isDestructuringAssignment(node)) {
89334                 return visitDestructuringAssignment(node);
89335             }
89336             else {
89337                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89338             }
89339         }
89340         function destructuringNeedsFlattening(node) {
89341             if (ts.isObjectLiteralExpression(node)) {
89342                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89343                     var elem = _a[_i];
89344                     switch (elem.kind) {
89345                         case 281 /* PropertyAssignment */:
89346                             if (destructuringNeedsFlattening(elem.initializer)) {
89347                                 return true;
89348                             }
89349                             break;
89350                         case 282 /* ShorthandPropertyAssignment */:
89351                             if (destructuringNeedsFlattening(elem.name)) {
89352                                 return true;
89353                             }
89354                             break;
89355                         case 283 /* SpreadAssignment */:
89356                             if (destructuringNeedsFlattening(elem.expression)) {
89357                                 return true;
89358                             }
89359                             break;
89360                         case 161 /* MethodDeclaration */:
89361                         case 163 /* GetAccessor */:
89362                         case 164 /* SetAccessor */:
89363                             return false;
89364                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89365                     }
89366                 }
89367             }
89368             else if (ts.isArrayLiteralExpression(node)) {
89369                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89370                     var elem = _c[_b];
89371                     if (ts.isSpreadElement(elem)) {
89372                         if (destructuringNeedsFlattening(elem.expression)) {
89373                             return true;
89374                         }
89375                     }
89376                     else if (destructuringNeedsFlattening(elem)) {
89377                         return true;
89378                     }
89379                 }
89380             }
89381             else if (ts.isIdentifier(node)) {
89382                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89383             }
89384             return false;
89385         }
89386         function visitDestructuringAssignment(node) {
89387             if (destructuringNeedsFlattening(node.left)) {
89388                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89389             }
89390             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89391         }
89392         function visitImportCallExpression(node) {
89393             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89394             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89395             switch (compilerOptions.module) {
89396                 case ts.ModuleKind.AMD:
89397                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89398                 case ts.ModuleKind.UMD:
89399                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89400                 case ts.ModuleKind.CommonJS:
89401                 default:
89402                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89403             }
89404         }
89405         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89406             // (function (factory) {
89407             //      ... (regular UMD)
89408             // }
89409             // })(function (require, exports, useSyncRequire) {
89410             //      "use strict";
89411             //      Object.defineProperty(exports, "__esModule", { value: true });
89412             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89413             //      var __resolved = new Promise(function (resolve) { resolve(); });
89414             //      .....
89415             //      __syncRequire
89416             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89417             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89418             // });
89419             needUMDDynamicImportHelper = true;
89420             if (ts.isSimpleCopiableExpression(arg)) {
89421                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89422                 return ts.createConditional(
89423                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89424                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89425                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89426             }
89427             else {
89428                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89429                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89430                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89431                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89432                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89433             }
89434         }
89435         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89436             // improt("./blah")
89437             // emit as
89438             // define(["require", "exports", "blah"], function (require, exports) {
89439             //     ...
89440             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89441             // });
89442             var resolve = ts.createUniqueName("resolve");
89443             var reject = ts.createUniqueName("reject");
89444             var parameters = [
89445                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89446                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89447             ];
89448             var body = ts.createBlock([
89449                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89450                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89451             ]);
89452             var func;
89453             if (languageVersion >= 2 /* ES2015 */) {
89454                 func = ts.createArrowFunction(
89455                 /*modifiers*/ undefined, 
89456                 /*typeParameters*/ undefined, parameters, 
89457                 /*type*/ undefined, 
89458                 /*equalsGreaterThanToken*/ undefined, body);
89459             }
89460             else {
89461                 func = ts.createFunctionExpression(
89462                 /*modifiers*/ undefined, 
89463                 /*asteriskToken*/ undefined, 
89464                 /*name*/ undefined, 
89465                 /*typeParameters*/ undefined, parameters, 
89466                 /*type*/ undefined, body);
89467                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89468                 // that this new function expression indicates it captures 'this' so that the
89469                 // es2015 transformer will properly substitute 'this' with '_this'.
89470                 if (containsLexicalThis) {
89471                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89472                 }
89473             }
89474             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89475             if (compilerOptions.esModuleInterop) {
89476                 context.requestEmitHelper(ts.importStarHelper);
89477                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89478             }
89479             return promise;
89480         }
89481         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89482             // import("./blah")
89483             // emit as
89484             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89485             // We have to wrap require in then callback so that require is done in asynchronously
89486             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89487             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89488             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89489             if (compilerOptions.esModuleInterop) {
89490                 context.requestEmitHelper(ts.importStarHelper);
89491                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89492             }
89493             var func;
89494             if (languageVersion >= 2 /* ES2015 */) {
89495                 func = ts.createArrowFunction(
89496                 /*modifiers*/ undefined, 
89497                 /*typeParameters*/ undefined, 
89498                 /*parameters*/ [], 
89499                 /*type*/ undefined, 
89500                 /*equalsGreaterThanToken*/ undefined, requireCall);
89501             }
89502             else {
89503                 func = ts.createFunctionExpression(
89504                 /*modifiers*/ undefined, 
89505                 /*asteriskToken*/ undefined, 
89506                 /*name*/ undefined, 
89507                 /*typeParameters*/ undefined, 
89508                 /*parameters*/ [], 
89509                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89510                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89511                 // that this new function expression indicates it captures 'this' so that the
89512                 // es2015 transformer will properly substitute 'this' with '_this'.
89513                 if (containsLexicalThis) {
89514                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89515                 }
89516             }
89517             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89518         }
89519         function getHelperExpressionForExport(node, innerExpr) {
89520             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89521                 return innerExpr;
89522             }
89523             if (ts.getExportNeedsImportStarHelper(node)) {
89524                 context.requestEmitHelper(ts.importStarHelper);
89525                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89526             }
89527             return innerExpr;
89528         }
89529         function getHelperExpressionForImport(node, innerExpr) {
89530             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89531                 return innerExpr;
89532             }
89533             if (ts.getImportNeedsImportStarHelper(node)) {
89534                 context.requestEmitHelper(ts.importStarHelper);
89535                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89536             }
89537             if (ts.getImportNeedsImportDefaultHelper(node)) {
89538                 context.requestEmitHelper(ts.importDefaultHelper);
89539                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89540             }
89541             return innerExpr;
89542         }
89543         /**
89544          * Visits an ImportDeclaration node.
89545          *
89546          * @param node The node to visit.
89547          */
89548         function visitImportDeclaration(node) {
89549             var statements;
89550             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89551             if (moduleKind !== ts.ModuleKind.AMD) {
89552                 if (!node.importClause) {
89553                     // import "mod";
89554                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89555                 }
89556                 else {
89557                     var variables = [];
89558                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89559                         // import * as n from "mod";
89560                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89561                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89562                     }
89563                     else {
89564                         // import d from "mod";
89565                         // import { x, y } from "mod";
89566                         // import d, { x, y } from "mod";
89567                         // import d, * as n from "mod";
89568                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89569                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89570                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89571                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89572                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89573                         }
89574                     }
89575                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89576                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89577                     /*location*/ node), 
89578                     /*original*/ node));
89579                 }
89580             }
89581             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89582                 // import d, * as n from "mod";
89583                 statements = ts.append(statements, ts.createVariableStatement(
89584                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89585                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89586                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89587                     /*location*/ node), 
89588                     /*original*/ node)
89589                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89590             }
89591             if (hasAssociatedEndOfDeclarationMarker(node)) {
89592                 // Defer exports until we encounter an EndOfDeclarationMarker node
89593                 var id = ts.getOriginalNodeId(node);
89594                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89595             }
89596             else {
89597                 statements = appendExportsOfImportDeclaration(statements, node);
89598             }
89599             return ts.singleOrMany(statements);
89600         }
89601         /**
89602          * Creates a `require()` call to import an external module.
89603          *
89604          * @param importNode The declararation to import.
89605          */
89606         function createRequireCall(importNode) {
89607             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89608             var args = [];
89609             if (moduleName) {
89610                 args.push(moduleName);
89611             }
89612             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89613         }
89614         /**
89615          * Visits an ImportEqualsDeclaration node.
89616          *
89617          * @param node The node to visit.
89618          */
89619         function visitImportEqualsDeclaration(node) {
89620             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89621             var statements;
89622             if (moduleKind !== ts.ModuleKind.AMD) {
89623                 if (ts.hasModifier(node, 1 /* Export */)) {
89624                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89625                 }
89626                 else {
89627                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89628                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89629                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89630                         /*type*/ undefined, createRequireCall(node))
89631                     ], 
89632                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89633                 }
89634             }
89635             else {
89636                 if (ts.hasModifier(node, 1 /* Export */)) {
89637                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89638                 }
89639             }
89640             if (hasAssociatedEndOfDeclarationMarker(node)) {
89641                 // Defer exports until we encounter an EndOfDeclarationMarker node
89642                 var id = ts.getOriginalNodeId(node);
89643                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89644             }
89645             else {
89646                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89647             }
89648             return ts.singleOrMany(statements);
89649         }
89650         /**
89651          * Visits an ExportDeclaration node.
89652          *
89653          * @param The node to visit.
89654          */
89655         function visitExportDeclaration(node) {
89656             if (!node.moduleSpecifier) {
89657                 // Elide export declarations with no module specifier as they are handled
89658                 // elsewhere.
89659                 return undefined;
89660             }
89661             var generatedName = ts.getGeneratedNameForNode(node);
89662             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89663                 var statements = [];
89664                 // export { x, y } from "mod";
89665                 if (moduleKind !== ts.ModuleKind.AMD) {
89666                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89667                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89668                         ts.createVariableDeclaration(generatedName, 
89669                         /*type*/ undefined, createRequireCall(node))
89670                     ])), 
89671                     /*location*/ node), 
89672                     /* original */ node));
89673                 }
89674                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89675                     var specifier = _a[_i];
89676                     if (languageVersion === 0 /* ES3 */) {
89677                         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));
89678                     }
89679                     else {
89680                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89681                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89682                     }
89683                 }
89684                 return ts.singleOrMany(statements);
89685             }
89686             else if (node.exportClause) {
89687                 var statements = [];
89688                 // export * as ns from "mod";
89689                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89690                     getHelperExpressionForExport(node, createRequireCall(node)) :
89691                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89692                 return ts.singleOrMany(statements);
89693             }
89694             else {
89695                 // export * from "mod";
89696                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89697             }
89698         }
89699         /**
89700          * Visits an ExportAssignment node.
89701          *
89702          * @param node The node to visit.
89703          */
89704         function visitExportAssignment(node) {
89705             if (node.isExportEquals) {
89706                 return undefined;
89707             }
89708             var statements;
89709             var original = node.original;
89710             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89711                 // Defer exports until we encounter an EndOfDeclarationMarker node
89712                 var id = ts.getOriginalNodeId(node);
89713                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89714             }
89715             else {
89716                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89717             }
89718             return ts.singleOrMany(statements);
89719         }
89720         /**
89721          * Visits a FunctionDeclaration node.
89722          *
89723          * @param node The node to visit.
89724          */
89725         function visitFunctionDeclaration(node) {
89726             var statements;
89727             if (ts.hasModifier(node, 1 /* Export */)) {
89728                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89729                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89730                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89731                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89732                 /*location*/ node), 
89733                 /*original*/ node));
89734             }
89735             else {
89736                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89737             }
89738             if (hasAssociatedEndOfDeclarationMarker(node)) {
89739                 // Defer exports until we encounter an EndOfDeclarationMarker node
89740                 var id = ts.getOriginalNodeId(node);
89741                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89742             }
89743             else {
89744                 statements = appendExportsOfHoistedDeclaration(statements, node);
89745             }
89746             return ts.singleOrMany(statements);
89747         }
89748         /**
89749          * Visits a ClassDeclaration node.
89750          *
89751          * @param node The node to visit.
89752          */
89753         function visitClassDeclaration(node) {
89754             var statements;
89755             if (ts.hasModifier(node, 1 /* Export */)) {
89756                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89757                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89758                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89759             }
89760             else {
89761                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89762             }
89763             if (hasAssociatedEndOfDeclarationMarker(node)) {
89764                 // Defer exports until we encounter an EndOfDeclarationMarker node
89765                 var id = ts.getOriginalNodeId(node);
89766                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89767             }
89768             else {
89769                 statements = appendExportsOfHoistedDeclaration(statements, node);
89770             }
89771             return ts.singleOrMany(statements);
89772         }
89773         /**
89774          * Visits a VariableStatement node.
89775          *
89776          * @param node The node to visit.
89777          */
89778         function visitVariableStatement(node) {
89779             var statements;
89780             var variables;
89781             var expressions;
89782             if (ts.hasModifier(node, 1 /* Export */)) {
89783                 var modifiers = void 0;
89784                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89785                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89786                     var variable = _a[_i];
89787                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89788                         if (!modifiers) {
89789                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89790                         }
89791                         variables = ts.append(variables, variable);
89792                     }
89793                     else if (variable.initializer) {
89794                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89795                     }
89796                 }
89797                 if (variables) {
89798                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89799                 }
89800                 if (expressions) {
89801                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89802                 }
89803             }
89804             else {
89805                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89806             }
89807             if (hasAssociatedEndOfDeclarationMarker(node)) {
89808                 // Defer exports until we encounter an EndOfDeclarationMarker node
89809                 var id = ts.getOriginalNodeId(node);
89810                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89811             }
89812             else {
89813                 statements = appendExportsOfVariableStatement(statements, node);
89814             }
89815             return ts.singleOrMany(statements);
89816         }
89817         function createAllExportExpressions(name, value, location) {
89818             var exportedNames = getExports(name);
89819             if (exportedNames) {
89820                 // For each additional export of the declaration, apply an export assignment.
89821                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
89822                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
89823                     var exportName = exportedNames_1[_i];
89824                     // Mark the node to prevent triggering substitution.
89825                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
89826                     expression = createExportExpression(exportName, expression, /*location*/ location);
89827                 }
89828                 return expression;
89829             }
89830             return ts.createAssignment(name, value);
89831         }
89832         /**
89833          * Transforms an exported variable with an initializer into an expression.
89834          *
89835          * @param node The node to transform.
89836          */
89837         function transformInitializedVariable(node) {
89838             if (ts.isBindingPattern(node.name)) {
89839                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
89840                 /*visitor*/ undefined, context, 0 /* All */, 
89841                 /*needsValue*/ false, createAllExportExpressions);
89842             }
89843             else {
89844                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
89845                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
89846             }
89847         }
89848         /**
89849          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
89850          * and transformed declaration.
89851          *
89852          * @param node The node to visit.
89853          */
89854         function visitMergeDeclarationMarker(node) {
89855             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
89856             // declaration we do not emit a leading variable declaration. To preserve the
89857             // begin/end semantics of the declararation and to properly handle exports
89858             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
89859             //
89860             // To balance the declaration, add the exports of the elided variable
89861             // statement.
89862             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
89863                 var id = ts.getOriginalNodeId(node);
89864                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
89865             }
89866             return node;
89867         }
89868         /**
89869          * Determines whether a node has an associated EndOfDeclarationMarker.
89870          *
89871          * @param node The node to test.
89872          */
89873         function hasAssociatedEndOfDeclarationMarker(node) {
89874             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
89875         }
89876         /**
89877          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
89878          * declaration.
89879          *
89880          * @param node The node to visit.
89881          */
89882         function visitEndOfDeclarationMarker(node) {
89883             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
89884             // end of the transformed declaration. We use this marker to emit any deferred exports
89885             // of the declaration.
89886             var id = ts.getOriginalNodeId(node);
89887             var statements = deferredExports[id];
89888             if (statements) {
89889                 delete deferredExports[id];
89890                 return ts.append(statements, node);
89891             }
89892             return node;
89893         }
89894         /**
89895          * Appends the exports of an ImportDeclaration to a statement list, returning the
89896          * statement list.
89897          *
89898          * @param statements A statement list to which the down-level export statements are to be
89899          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89900          * appended.
89901          * @param decl The declaration whose exports are to be recorded.
89902          */
89903         function appendExportsOfImportDeclaration(statements, decl) {
89904             if (currentModuleInfo.exportEquals) {
89905                 return statements;
89906             }
89907             var importClause = decl.importClause;
89908             if (!importClause) {
89909                 return statements;
89910             }
89911             if (importClause.name) {
89912                 statements = appendExportsOfDeclaration(statements, importClause);
89913             }
89914             var namedBindings = importClause.namedBindings;
89915             if (namedBindings) {
89916                 switch (namedBindings.kind) {
89917                     case 256 /* NamespaceImport */:
89918                         statements = appendExportsOfDeclaration(statements, namedBindings);
89919                         break;
89920                     case 257 /* NamedImports */:
89921                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
89922                             var importBinding = _a[_i];
89923                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
89924                         }
89925                         break;
89926                 }
89927             }
89928             return statements;
89929         }
89930         /**
89931          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
89932          * statement list.
89933          *
89934          * @param statements A statement list to which the down-level export statements are to be
89935          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89936          * appended.
89937          * @param decl The declaration whose exports are to be recorded.
89938          */
89939         function appendExportsOfImportEqualsDeclaration(statements, decl) {
89940             if (currentModuleInfo.exportEquals) {
89941                 return statements;
89942             }
89943             return appendExportsOfDeclaration(statements, decl);
89944         }
89945         /**
89946          * Appends the exports of a VariableStatement to a statement list, returning the statement
89947          * list.
89948          *
89949          * @param statements A statement list to which the down-level export statements are to be
89950          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89951          * appended.
89952          * @param node The VariableStatement whose exports are to be recorded.
89953          */
89954         function appendExportsOfVariableStatement(statements, node) {
89955             if (currentModuleInfo.exportEquals) {
89956                 return statements;
89957             }
89958             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89959                 var decl = _a[_i];
89960                 statements = appendExportsOfBindingElement(statements, decl);
89961             }
89962             return statements;
89963         }
89964         /**
89965          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
89966          * returning the statement list.
89967          *
89968          * @param statements A statement list to which the down-level export statements are to be
89969          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89970          * appended.
89971          * @param decl The declaration whose exports are to be recorded.
89972          */
89973         function appendExportsOfBindingElement(statements, decl) {
89974             if (currentModuleInfo.exportEquals) {
89975                 return statements;
89976             }
89977             if (ts.isBindingPattern(decl.name)) {
89978                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
89979                     var element = _a[_i];
89980                     if (!ts.isOmittedExpression(element)) {
89981                         statements = appendExportsOfBindingElement(statements, element);
89982                     }
89983                 }
89984             }
89985             else if (!ts.isGeneratedIdentifier(decl.name)) {
89986                 statements = appendExportsOfDeclaration(statements, decl);
89987             }
89988             return statements;
89989         }
89990         /**
89991          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
89992          * returning the statement list.
89993          *
89994          * @param statements A statement list to which the down-level export statements are to be
89995          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89996          * appended.
89997          * @param decl The declaration whose exports are to be recorded.
89998          */
89999         function appendExportsOfHoistedDeclaration(statements, decl) {
90000             if (currentModuleInfo.exportEquals) {
90001                 return statements;
90002             }
90003             if (ts.hasModifier(decl, 1 /* Export */)) {
90004                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90005                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90006             }
90007             if (decl.name) {
90008                 statements = appendExportsOfDeclaration(statements, decl);
90009             }
90010             return statements;
90011         }
90012         /**
90013          * Appends the exports of a declaration to a statement list, 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 to export.
90019          */
90020         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90021             var name = ts.getDeclarationName(decl);
90022             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90023             if (exportSpecifiers) {
90024                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90025                     var exportSpecifier = exportSpecifiers_1[_i];
90026                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90027                 }
90028             }
90029             return statements;
90030         }
90031         /**
90032          * Appends the down-level representation of an export to a statement list, returning the
90033          * statement list.
90034          *
90035          * @param statements A statement list to which the down-level export statements are to be
90036          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90037          * appended.
90038          * @param exportName The name of the export.
90039          * @param expression The expression to export.
90040          * @param location The location to use for source maps and comments for the export.
90041          * @param allowComments Whether to allow comments on the export.
90042          */
90043         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90044             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90045             return statements;
90046         }
90047         function createUnderscoreUnderscoreESModule() {
90048             var statement;
90049             if (languageVersion === 0 /* ES3 */) {
90050                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90051             }
90052             else {
90053                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90054                 /*typeArguments*/ undefined, [
90055                     ts.createIdentifier("exports"),
90056                     ts.createLiteral("__esModule"),
90057                     ts.createObjectLiteral([
90058                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90059                     ])
90060                 ]));
90061             }
90062             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90063             return statement;
90064         }
90065         /**
90066          * Creates a call to the current file's export function to export a value.
90067          *
90068          * @param name The bound name of the export.
90069          * @param value The exported value.
90070          * @param location The location to use for source maps and comments for the export.
90071          * @param allowComments An optional value indicating whether to emit comments for the statement.
90072          */
90073         function createExportStatement(name, value, location, allowComments, liveBinding) {
90074             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90075             ts.startOnNewLine(statement);
90076             if (!allowComments) {
90077                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90078             }
90079             return statement;
90080         }
90081         /**
90082          * Creates a call to the current file's export function to export a value.
90083          *
90084          * @param name The bound name of the export.
90085          * @param value The exported value.
90086          * @param location The location to use for source maps and comments for the export.
90087          */
90088         function createExportExpression(name, value, location, liveBinding) {
90089             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90090             /*typeArguments*/ undefined, [
90091                 ts.createIdentifier("exports"),
90092                 ts.createLiteral(name),
90093                 ts.createObjectLiteral([
90094                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90095                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90096                     /*modifiers*/ undefined, 
90097                     /*asteriskToken*/ undefined, 
90098                     /*name*/ undefined, 
90099                     /*typeParameters*/ undefined, 
90100                     /*parameters*/ [], 
90101                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90102                 ])
90103             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90104         }
90105         //
90106         // Modifier Visitors
90107         //
90108         /**
90109          * Visit nodes to elide module-specific modifiers.
90110          *
90111          * @param node The node to visit.
90112          */
90113         function modifierVisitor(node) {
90114             // Elide module-specific modifiers.
90115             switch (node.kind) {
90116                 case 89 /* ExportKeyword */:
90117                 case 84 /* DefaultKeyword */:
90118                     return undefined;
90119             }
90120             return node;
90121         }
90122         //
90123         // Emit Notification
90124         //
90125         /**
90126          * Hook for node emit notifications.
90127          *
90128          * @param hint A hint as to the intended usage of the node.
90129          * @param node The node to emit.
90130          * @param emit A callback used to emit the node in the printer.
90131          */
90132         function onEmitNode(hint, node, emitCallback) {
90133             if (node.kind === 290 /* SourceFile */) {
90134                 currentSourceFile = node;
90135                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90136                 noSubstitution = [];
90137                 previousOnEmitNode(hint, node, emitCallback);
90138                 currentSourceFile = undefined;
90139                 currentModuleInfo = undefined;
90140                 noSubstitution = undefined;
90141             }
90142             else {
90143                 previousOnEmitNode(hint, node, emitCallback);
90144             }
90145         }
90146         //
90147         // Substitutions
90148         //
90149         /**
90150          * Hooks node substitutions.
90151          *
90152          * @param hint A hint as to the intended usage of the node.
90153          * @param node The node to substitute.
90154          */
90155         function onSubstituteNode(hint, node) {
90156             node = previousOnSubstituteNode(hint, node);
90157             if (node.id && noSubstitution[node.id]) {
90158                 return node;
90159             }
90160             if (hint === 1 /* Expression */) {
90161                 return substituteExpression(node);
90162             }
90163             else if (ts.isShorthandPropertyAssignment(node)) {
90164                 return substituteShorthandPropertyAssignment(node);
90165             }
90166             return node;
90167         }
90168         /**
90169          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90170          * or exported symbol.
90171          *
90172          * @param node The node to substitute.
90173          */
90174         function substituteShorthandPropertyAssignment(node) {
90175             var name = node.name;
90176             var exportedOrImportedName = substituteExpressionIdentifier(name);
90177             if (exportedOrImportedName !== name) {
90178                 // A shorthand property with an assignment initializer is probably part of a
90179                 // destructuring assignment
90180                 if (node.objectAssignmentInitializer) {
90181                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90182                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90183                 }
90184                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90185             }
90186             return node;
90187         }
90188         /**
90189          * Substitution for an Expression that may contain an imported or exported symbol.
90190          *
90191          * @param node The node to substitute.
90192          */
90193         function substituteExpression(node) {
90194             switch (node.kind) {
90195                 case 75 /* Identifier */:
90196                     return substituteExpressionIdentifier(node);
90197                 case 209 /* BinaryExpression */:
90198                     return substituteBinaryExpression(node);
90199                 case 208 /* PostfixUnaryExpression */:
90200                 case 207 /* PrefixUnaryExpression */:
90201                     return substituteUnaryExpression(node);
90202             }
90203             return node;
90204         }
90205         /**
90206          * Substitution for an Identifier expression that may contain an imported or exported
90207          * symbol.
90208          *
90209          * @param node The node to substitute.
90210          */
90211         function substituteExpressionIdentifier(node) {
90212             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90213                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90214                 if (externalHelpersModuleName) {
90215                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90216                 }
90217                 return node;
90218             }
90219             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90220                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90221                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90222                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90223                     /*location*/ node);
90224                 }
90225                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90226                 if (importDeclaration) {
90227                     if (ts.isImportClause(importDeclaration)) {
90228                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90229                         /*location*/ node);
90230                     }
90231                     else if (ts.isImportSpecifier(importDeclaration)) {
90232                         var name = importDeclaration.propertyName || importDeclaration.name;
90233                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90234                         /*location*/ node);
90235                     }
90236                 }
90237             }
90238             return node;
90239         }
90240         /**
90241          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90242          *
90243          * @param node The node to substitute.
90244          */
90245         function substituteBinaryExpression(node) {
90246             // When we see an assignment expression whose left-hand side is an exported symbol,
90247             // we should ensure all exports of that symbol are updated with the correct value.
90248             //
90249             // - We do not substitute generated identifiers for any reason.
90250             // - We do not substitute identifiers tagged with the LocalName flag.
90251             // - We do not substitute identifiers that were originally the name of an enum or
90252             //   namespace due to how they are transformed in TypeScript.
90253             // - We only substitute identifiers that are exported at the top level.
90254             if (ts.isAssignmentOperator(node.operatorToken.kind)
90255                 && ts.isIdentifier(node.left)
90256                 && !ts.isGeneratedIdentifier(node.left)
90257                 && !ts.isLocalName(node.left)
90258                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90259                 var exportedNames = getExports(node.left);
90260                 if (exportedNames) {
90261                     // For each additional export of the declaration, apply an export assignment.
90262                     var expression = node;
90263                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90264                         var exportName = exportedNames_2[_i];
90265                         // Mark the node to prevent triggering this rule again.
90266                         noSubstitution[ts.getNodeId(expression)] = true;
90267                         expression = createExportExpression(exportName, expression, /*location*/ node);
90268                     }
90269                     return expression;
90270                 }
90271             }
90272             return node;
90273         }
90274         /**
90275          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90276          *
90277          * @param node The node to substitute.
90278          */
90279         function substituteUnaryExpression(node) {
90280             // When we see a prefix or postfix increment expression whose operand is an exported
90281             // symbol, we should ensure all exports of that symbol are updated with the correct
90282             // value.
90283             //
90284             // - We do not substitute generated identifiers for any reason.
90285             // - We do not substitute identifiers tagged with the LocalName flag.
90286             // - We do not substitute identifiers that were originally the name of an enum or
90287             //   namespace due to how they are transformed in TypeScript.
90288             // - We only substitute identifiers that are exported at the top level.
90289             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90290                 && ts.isIdentifier(node.operand)
90291                 && !ts.isGeneratedIdentifier(node.operand)
90292                 && !ts.isLocalName(node.operand)
90293                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90294                 var exportedNames = getExports(node.operand);
90295                 if (exportedNames) {
90296                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90297                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90298                         /*location*/ node)
90299                         : node;
90300                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90301                         var exportName = exportedNames_3[_i];
90302                         // Mark the node to prevent triggering this rule again.
90303                         noSubstitution[ts.getNodeId(expression)] = true;
90304                         expression = createExportExpression(exportName, expression);
90305                     }
90306                     return expression;
90307                 }
90308             }
90309             return node;
90310         }
90311         /**
90312          * Gets the additional exports of a name.
90313          *
90314          * @param name The name.
90315          */
90316         function getExports(name) {
90317             if (!ts.isGeneratedIdentifier(name)) {
90318                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90319                     || resolver.getReferencedValueDeclaration(name);
90320                 if (valueDeclaration) {
90321                     return currentModuleInfo
90322                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90323                 }
90324             }
90325         }
90326     }
90327     ts.transformModule = transformModule;
90328     ts.createBindingHelper = {
90329         name: "typescript:commonjscreatebinding",
90330         importName: "__createBinding",
90331         scoped: false,
90332         priority: 1,
90333         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}));"
90334     };
90335     function createCreateBindingHelper(context, module, inputName, outputName) {
90336         context.requestEmitHelper(ts.createBindingHelper);
90337         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90338     }
90339     ts.setModuleDefaultHelper = {
90340         name: "typescript:commonjscreatevalue",
90341         importName: "__setModuleDefault",
90342         scoped: false,
90343         priority: 1,
90344         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});"
90345     };
90346     // emit output for the __export helper function
90347     var exportStarHelper = {
90348         name: "typescript:export-star",
90349         importName: "__exportStar",
90350         scoped: false,
90351         dependencies: [ts.createBindingHelper],
90352         priority: 2,
90353         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            };"
90354     };
90355     function createExportStarHelper(context, module) {
90356         context.requestEmitHelper(exportStarHelper);
90357         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90358     }
90359     // emit helper for dynamic import
90360     var dynamicImportUMDHelper = {
90361         name: "typescript:dynamicimport-sync-require",
90362         scoped: true,
90363         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90364     };
90365     // emit helper for `import * as Name from "foo"`
90366     ts.importStarHelper = {
90367         name: "typescript:commonjsimportstar",
90368         importName: "__importStar",
90369         scoped: false,
90370         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90371         priority: 2,
90372         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};"
90373     };
90374     // emit helper for `import Name from "foo"`
90375     ts.importDefaultHelper = {
90376         name: "typescript:commonjsimportdefault",
90377         importName: "__importDefault",
90378         scoped: false,
90379         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90380     };
90381 })(ts || (ts = {}));
90382 /*@internal*/
90383 var ts;
90384 (function (ts) {
90385     function transformSystemModule(context) {
90386         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90387         var compilerOptions = context.getCompilerOptions();
90388         var resolver = context.getEmitResolver();
90389         var host = context.getEmitHost();
90390         var previousOnSubstituteNode = context.onSubstituteNode;
90391         var previousOnEmitNode = context.onEmitNode;
90392         context.onSubstituteNode = onSubstituteNode;
90393         context.onEmitNode = onEmitNode;
90394         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90395         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90396         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90397         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90398         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90399         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90400         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90401         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90402         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90403         var exportFunctionsMap = []; // The export function associated with a source file.
90404         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90405         var contextObjectMap = []; // The context object associated with a source file.
90406         var currentSourceFile; // The current file.
90407         var moduleInfo; // ExternalModuleInfo for the current file.
90408         var exportFunction; // The export function for the current file.
90409         var contextObject; // The context object for the current file.
90410         var hoistedStatements;
90411         var enclosingBlockScopedContainer;
90412         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90413         return ts.chainBundle(transformSourceFile);
90414         /**
90415          * Transforms the module aspects of a SourceFile.
90416          *
90417          * @param node The SourceFile node.
90418          */
90419         function transformSourceFile(node) {
90420             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90421                 return node;
90422             }
90423             var id = ts.getOriginalNodeId(node);
90424             currentSourceFile = node;
90425             enclosingBlockScopedContainer = node;
90426             // System modules have the following shape:
90427             //
90428             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90429             //
90430             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90431             // is used to publish exported values. 'exports' returns its 'value' argument so in
90432             // most cases expressions that mutate exported values can be rewritten as:
90433             //
90434             //     expr -> exports('name', expr)
90435             //
90436             // The only exception in this rule is postfix unary operators,
90437             // see comment to 'substitutePostfixUnaryExpression' for more details
90438             // Collect information about the external module and dependency groups.
90439             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90440             // Make sure that the name of the 'exports' function does not conflict with
90441             // existing identifiers.
90442             exportFunction = ts.createUniqueName("exports");
90443             exportFunctionsMap[id] = exportFunction;
90444             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90445             // Add the body of the module.
90446             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90447             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90448             var moduleBodyFunction = ts.createFunctionExpression(
90449             /*modifiers*/ undefined, 
90450             /*asteriskToken*/ undefined, 
90451             /*name*/ undefined, 
90452             /*typeParameters*/ undefined, [
90453                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90454                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90455             ], 
90456             /*type*/ undefined, moduleBodyBlock);
90457             // Write the call to `System.register`
90458             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90459             // So the helper will be emit at the correct position instead of at the top of the source-file
90460             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90461             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90462             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90463                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90464                 /*typeArguments*/ undefined, moduleName
90465                     ? [moduleName, dependencies, moduleBodyFunction]
90466                     : [dependencies, moduleBodyFunction]))
90467             ]), node.statements)), 1024 /* NoTrailingComments */);
90468             if (!(compilerOptions.outFile || compilerOptions.out)) {
90469                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90470             }
90471             if (noSubstitution) {
90472                 noSubstitutionMap[id] = noSubstitution;
90473                 noSubstitution = undefined;
90474             }
90475             currentSourceFile = undefined;
90476             moduleInfo = undefined;
90477             exportFunction = undefined;
90478             contextObject = undefined;
90479             hoistedStatements = undefined;
90480             enclosingBlockScopedContainer = undefined;
90481             return ts.aggregateTransformFlags(updated);
90482         }
90483         /**
90484          * Collects the dependency groups for this files imports.
90485          *
90486          * @param externalImports The imports for the file.
90487          */
90488         function collectDependencyGroups(externalImports) {
90489             var groupIndices = ts.createMap();
90490             var dependencyGroups = [];
90491             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90492                 var externalImport = externalImports_1[_i];
90493                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90494                 if (externalModuleName) {
90495                     var text = externalModuleName.text;
90496                     var groupIndex = groupIndices.get(text);
90497                     if (groupIndex !== undefined) {
90498                         // deduplicate/group entries in dependency list by the dependency name
90499                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90500                     }
90501                     else {
90502                         groupIndices.set(text, dependencyGroups.length);
90503                         dependencyGroups.push({
90504                             name: externalModuleName,
90505                             externalImports: [externalImport]
90506                         });
90507                     }
90508                 }
90509             }
90510             return dependencyGroups;
90511         }
90512         /**
90513          * Adds the statements for the module body function for the source file.
90514          *
90515          * @param node The source file for the module.
90516          * @param dependencyGroups The grouped dependencies of the module.
90517          */
90518         function createSystemModuleBody(node, dependencyGroups) {
90519             // Shape of the body in system modules:
90520             //
90521             //  function (exports) {
90522             //      <list of local aliases for imports>
90523             //      <hoisted variable declarations>
90524             //      <hoisted function declarations>
90525             //      return {
90526             //          setters: [
90527             //              <list of setter function for imports>
90528             //          ],
90529             //          execute: function() {
90530             //              <module statements>
90531             //          }
90532             //      }
90533             //      <temp declarations>
90534             //  }
90535             //
90536             // i.e:
90537             //
90538             //   import {x} from 'file1'
90539             //   var y = 1;
90540             //   export function foo() { return y + x(); }
90541             //   console.log(y);
90542             //
90543             // Will be transformed to:
90544             //
90545             //  function(exports) {
90546             //      function foo() { return y + file_1.x(); }
90547             //      exports("foo", foo);
90548             //      var file_1, y;
90549             //      return {
90550             //          setters: [
90551             //              function(v) { file_1 = v }
90552             //          ],
90553             //          execute(): function() {
90554             //              y = 1;
90555             //              console.log(y);
90556             //          }
90557             //      };
90558             //  }
90559             var statements = [];
90560             // We start a new lexical environment in this function body, but *not* in the
90561             // body of the execute function. This allows us to emit temporary declarations
90562             // only in the outer module body and not in the inner one.
90563             startLexicalEnvironment();
90564             // Add any prologue directives.
90565             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90566             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90567             // var __moduleName = context_1 && context_1.id;
90568             statements.push(ts.createVariableStatement(
90569             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90570                 ts.createVariableDeclaration("__moduleName", 
90571                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90572             ])));
90573             // Visit the synthetic external helpers import declaration if present
90574             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90575             // Visit the statements of the source file, emitting any transformations into
90576             // the `executeStatements` array. We do this *before* we fill the `setters` array
90577             // as we both emit transformations as well as aggregate some data used when creating
90578             // setters. This allows us to reduce the number of times we need to loop through the
90579             // statements of the source file.
90580             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90581             // Emit early exports for function declarations.
90582             ts.addRange(statements, hoistedStatements);
90583             // We emit hoisted variables early to align roughly with our previous emit output.
90584             // Two key differences in this approach are:
90585             // - Temporary variables will appear at the top rather than at the bottom of the file
90586             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90587             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90588             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90589                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90590                 undefined;
90591             var moduleObject = ts.createObjectLiteral([
90592                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90593                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90594                 /*asteriskToken*/ undefined, 
90595                 /*name*/ undefined, 
90596                 /*typeParameters*/ undefined, 
90597                 /*parameters*/ [], 
90598                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90599             ]);
90600             moduleObject.multiLine = true;
90601             statements.push(ts.createReturn(moduleObject));
90602             return ts.createBlock(statements, /*multiLine*/ true);
90603         }
90604         /**
90605          * Adds an exportStar function to a statement list if it is needed for the file.
90606          *
90607          * @param statements A statement list.
90608          */
90609         function addExportStarIfNeeded(statements) {
90610             if (!moduleInfo.hasExportStarsToExportValues) {
90611                 return;
90612             }
90613             // when resolving exports local exported entries/indirect exported entries in the module
90614             // should always win over entries with similar names that were added via star exports
90615             // to support this we store names of local/indirect exported entries in a set.
90616             // this set is used to filter names brought by star expors.
90617             // local names set should only be added if we have anything exported
90618             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90619                 // no exported declarations (export var ...) or export specifiers (export {x})
90620                 // check if we have any non star export declarations.
90621                 var hasExportDeclarationWithExportClause = false;
90622                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90623                     var externalImport = _a[_i];
90624                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90625                         hasExportDeclarationWithExportClause = true;
90626                         break;
90627                     }
90628                 }
90629                 if (!hasExportDeclarationWithExportClause) {
90630                     // we still need to emit exportStar helper
90631                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90632                     statements.push(exportStarFunction_1);
90633                     return exportStarFunction_1.name;
90634                 }
90635             }
90636             var exportedNames = [];
90637             if (moduleInfo.exportedNames) {
90638                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90639                     var exportedLocalName = _c[_b];
90640                     if (exportedLocalName.escapedText === "default") {
90641                         continue;
90642                     }
90643                     // write name of exported declaration, i.e 'export var x...'
90644                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90645                 }
90646             }
90647             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90648                 var externalImport = _e[_d];
90649                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90650                     continue;
90651                 }
90652                 if (!externalImport.exportClause) {
90653                     // export * from ...
90654                     continue;
90655                 }
90656                 if (ts.isNamedExports(externalImport.exportClause)) {
90657                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90658                         var element = _g[_f];
90659                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90660                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90661                     }
90662                 }
90663                 else {
90664                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90665                 }
90666             }
90667             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90668             statements.push(ts.createVariableStatement(
90669             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90670                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90671                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90672             ])));
90673             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90674             statements.push(exportStarFunction);
90675             return exportStarFunction.name;
90676         }
90677         /**
90678          * Creates an exportStar function for the file, with an optional set of excluded local
90679          * names.
90680          *
90681          * @param localNames An optional reference to an object containing a set of excluded local
90682          * names.
90683          */
90684         function createExportStarFunction(localNames) {
90685             var exportStarFunction = ts.createUniqueName("exportStar");
90686             var m = ts.createIdentifier("m");
90687             var n = ts.createIdentifier("n");
90688             var exports = ts.createIdentifier("exports");
90689             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90690             if (localNames) {
90691                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90692                 /*typeArguments*/ undefined, [n])));
90693             }
90694             return ts.createFunctionDeclaration(
90695             /*decorators*/ undefined, 
90696             /*modifiers*/ undefined, 
90697             /*asteriskToken*/ undefined, exportStarFunction, 
90698             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90699             /*type*/ undefined, ts.createBlock([
90700                 ts.createVariableStatement(
90701                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90702                     ts.createVariableDeclaration(exports, 
90703                     /*type*/ undefined, ts.createObjectLiteral([]))
90704                 ])),
90705                 ts.createForIn(ts.createVariableDeclarationList([
90706                     ts.createVariableDeclaration(n, /*type*/ undefined)
90707                 ]), m, ts.createBlock([
90708                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90709                 ])),
90710                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90711                 /*typeArguments*/ undefined, [exports]))
90712             ], /*multiline*/ true));
90713         }
90714         /**
90715          * Creates an array setter callbacks for each dependency group.
90716          *
90717          * @param exportStarFunction A reference to an exportStarFunction for the file.
90718          * @param dependencyGroups An array of grouped dependencies.
90719          */
90720         function createSettersArray(exportStarFunction, dependencyGroups) {
90721             var setters = [];
90722             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90723                 var group_2 = dependencyGroups_1[_i];
90724                 // derive a unique name for parameter from the first named entry in the group
90725                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90726                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90727                 var statements = [];
90728                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90729                     var entry = _b[_a];
90730                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90731                     switch (entry.kind) {
90732                         case 254 /* ImportDeclaration */:
90733                             if (!entry.importClause) {
90734                                 // 'import "..."' case
90735                                 // module is imported only for side-effects, no emit required
90736                                 break;
90737                             }
90738                         // falls through
90739                         case 253 /* ImportEqualsDeclaration */:
90740                             ts.Debug.assert(importVariableName !== undefined);
90741                             // save import into the local
90742                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90743                             break;
90744                         case 260 /* ExportDeclaration */:
90745                             ts.Debug.assert(importVariableName !== undefined);
90746                             if (entry.exportClause) {
90747                                 if (ts.isNamedExports(entry.exportClause)) {
90748                                     //  export {a, b as c} from 'foo'
90749                                     //
90750                                     // emit as:
90751                                     //
90752                                     //  exports_({
90753                                     //     "a": _["a"],
90754                                     //     "c": _["b"]
90755                                     //  });
90756                                     var properties = [];
90757                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90758                                         var e = _d[_c];
90759                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90760                                     }
90761                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90762                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90763                                 }
90764                                 else {
90765                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90766                                     /*typeArguments*/ undefined, [
90767                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90768                                         parameterName
90769                                     ])));
90770                                 }
90771                             }
90772                             else {
90773                                 //  export * from 'foo'
90774                                 //
90775                                 // emit as:
90776                                 //
90777                                 //  exportStar(foo_1_1);
90778                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90779                                 /*typeArguments*/ undefined, [parameterName])));
90780                             }
90781                             break;
90782                     }
90783                 }
90784                 setters.push(ts.createFunctionExpression(
90785                 /*modifiers*/ undefined, 
90786                 /*asteriskToken*/ undefined, 
90787                 /*name*/ undefined, 
90788                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90789                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90790             }
90791             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90792         }
90793         //
90794         // Top-level Source Element Visitors
90795         //
90796         /**
90797          * Visit source elements at the top-level of a module.
90798          *
90799          * @param node The node to visit.
90800          */
90801         function sourceElementVisitor(node) {
90802             switch (node.kind) {
90803                 case 254 /* ImportDeclaration */:
90804                     return visitImportDeclaration(node);
90805                 case 253 /* ImportEqualsDeclaration */:
90806                     return visitImportEqualsDeclaration(node);
90807                 case 260 /* ExportDeclaration */:
90808                     return visitExportDeclaration(node);
90809                 case 259 /* ExportAssignment */:
90810                     return visitExportAssignment(node);
90811                 default:
90812                     return nestedElementVisitor(node);
90813             }
90814         }
90815         /**
90816          * Visits an ImportDeclaration node.
90817          *
90818          * @param node The node to visit.
90819          */
90820         function visitImportDeclaration(node) {
90821             var statements;
90822             if (node.importClause) {
90823                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90824             }
90825             if (hasAssociatedEndOfDeclarationMarker(node)) {
90826                 // Defer exports until we encounter an EndOfDeclarationMarker node
90827                 var id = ts.getOriginalNodeId(node);
90828                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
90829             }
90830             else {
90831                 statements = appendExportsOfImportDeclaration(statements, node);
90832             }
90833             return ts.singleOrMany(statements);
90834         }
90835         function visitExportDeclaration(node) {
90836             ts.Debug.assertIsDefined(node);
90837             return undefined;
90838         }
90839         /**
90840          * Visits an ImportEqualsDeclaration node.
90841          *
90842          * @param node The node to visit.
90843          */
90844         function visitImportEqualsDeclaration(node) {
90845             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
90846             var statements;
90847             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90848             if (hasAssociatedEndOfDeclarationMarker(node)) {
90849                 // Defer exports until we encounter an EndOfDeclarationMarker node
90850                 var id = ts.getOriginalNodeId(node);
90851                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
90852             }
90853             else {
90854                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
90855             }
90856             return ts.singleOrMany(statements);
90857         }
90858         /**
90859          * Visits an ExportAssignment node.
90860          *
90861          * @param node The node to visit.
90862          */
90863         function visitExportAssignment(node) {
90864             if (node.isExportEquals) {
90865                 // Elide `export=` as it is illegal in a SystemJS module.
90866                 return undefined;
90867             }
90868             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
90869             var original = node.original;
90870             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
90871                 // Defer exports until we encounter an EndOfDeclarationMarker node
90872                 var id = ts.getOriginalNodeId(node);
90873                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
90874             }
90875             else {
90876                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
90877             }
90878         }
90879         /**
90880          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
90881          *
90882          * @param node The node to visit.
90883          */
90884         function visitFunctionDeclaration(node) {
90885             if (ts.hasModifier(node, 1 /* Export */)) {
90886                 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), 
90887                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
90888                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
90889             }
90890             else {
90891                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
90892             }
90893             if (hasAssociatedEndOfDeclarationMarker(node)) {
90894                 // Defer exports until we encounter an EndOfDeclarationMarker node
90895                 var id = ts.getOriginalNodeId(node);
90896                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90897             }
90898             else {
90899                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
90900             }
90901             return undefined;
90902         }
90903         /**
90904          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
90905          *
90906          * @param node The node to visit.
90907          */
90908         function visitClassDeclaration(node) {
90909             var statements;
90910             // Hoist the name of the class declaration to the outer module body function.
90911             var name = ts.getLocalName(node);
90912             hoistVariableDeclaration(name);
90913             // Rewrite the class declaration into an assignment of a class expression.
90914             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
90915             /*modifiers*/ undefined, node.name, 
90916             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
90917             if (hasAssociatedEndOfDeclarationMarker(node)) {
90918                 // Defer exports until we encounter an EndOfDeclarationMarker node
90919                 var id = ts.getOriginalNodeId(node);
90920                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90921             }
90922             else {
90923                 statements = appendExportsOfHoistedDeclaration(statements, node);
90924             }
90925             return ts.singleOrMany(statements);
90926         }
90927         /**
90928          * Visits a variable statement, hoisting declared names to the top-level module body.
90929          * Each declaration is rewritten into an assignment expression.
90930          *
90931          * @param node The node to visit.
90932          */
90933         function visitVariableStatement(node) {
90934             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
90935                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
90936             }
90937             var expressions;
90938             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
90939             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
90940             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90941                 var variable = _a[_i];
90942                 if (variable.initializer) {
90943                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
90944                 }
90945                 else {
90946                     hoistBindingElement(variable);
90947                 }
90948             }
90949             var statements;
90950             if (expressions) {
90951                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
90952             }
90953             if (isMarkedDeclaration) {
90954                 // Defer exports until we encounter an EndOfDeclarationMarker node
90955                 var id = ts.getOriginalNodeId(node);
90956                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
90957             }
90958             else {
90959                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
90960             }
90961             return ts.singleOrMany(statements);
90962         }
90963         /**
90964          * Hoists the declared names of a VariableDeclaration or BindingElement.
90965          *
90966          * @param node The declaration to hoist.
90967          */
90968         function hoistBindingElement(node) {
90969             if (ts.isBindingPattern(node.name)) {
90970                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
90971                     var element = _a[_i];
90972                     if (!ts.isOmittedExpression(element)) {
90973                         hoistBindingElement(element);
90974                     }
90975                 }
90976             }
90977             else {
90978                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
90979             }
90980         }
90981         /**
90982          * Determines whether a VariableDeclarationList should be hoisted.
90983          *
90984          * @param node The node to test.
90985          */
90986         function shouldHoistVariableDeclarationList(node) {
90987             // hoist only non-block scoped declarations or block scoped declarations parented by source file
90988             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
90989                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
90990                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
90991         }
90992         /**
90993          * Transform an initialized variable declaration into an expression.
90994          *
90995          * @param node The node to transform.
90996          * @param isExportedDeclaration A value indicating whether the variable is exported.
90997          */
90998         function transformInitializedVariable(node, isExportedDeclaration) {
90999             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91000             return ts.isBindingPattern(node.name)
91001                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91002                 /*needsValue*/ false, createAssignment)
91003                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91004         }
91005         /**
91006          * Creates an assignment expression for an exported variable declaration.
91007          *
91008          * @param name The name of the variable.
91009          * @param value The value of the variable's initializer.
91010          * @param location The source map location for the assignment.
91011          */
91012         function createExportedVariableAssignment(name, value, location) {
91013             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91014         }
91015         /**
91016          * Creates an assignment expression for a non-exported variable declaration.
91017          *
91018          * @param name The name of the variable.
91019          * @param value The value of the variable's initializer.
91020          * @param location The source map location for the assignment.
91021          */
91022         function createNonExportedVariableAssignment(name, value, location) {
91023             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91024         }
91025         /**
91026          * Creates an assignment expression for a variable declaration.
91027          *
91028          * @param name The name of the variable.
91029          * @param value The value of the variable's initializer.
91030          * @param location The source map location for the assignment.
91031          * @param isExportedDeclaration A value indicating whether the variable is exported.
91032          */
91033         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91034             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91035             return isExportedDeclaration
91036                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91037                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91038         }
91039         /**
91040          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91041          * and transformed declaration.
91042          *
91043          * @param node The node to visit.
91044          */
91045         function visitMergeDeclarationMarker(node) {
91046             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91047             // declaration we do not emit a leading variable declaration. To preserve the
91048             // begin/end semantics of the declararation and to properly handle exports
91049             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91050             //
91051             // To balance the declaration, we defer the exports of the elided variable
91052             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91053             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91054                 var id = ts.getOriginalNodeId(node);
91055                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91056                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91057             }
91058             return node;
91059         }
91060         /**
91061          * Determines whether a node has an associated EndOfDeclarationMarker.
91062          *
91063          * @param node The node to test.
91064          */
91065         function hasAssociatedEndOfDeclarationMarker(node) {
91066             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91067         }
91068         /**
91069          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91070          * declaration.
91071          *
91072          * @param node The node to visit.
91073          */
91074         function visitEndOfDeclarationMarker(node) {
91075             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91076             // end of the transformed declaration. We use this marker to emit any deferred exports
91077             // of the declaration.
91078             var id = ts.getOriginalNodeId(node);
91079             var statements = deferredExports[id];
91080             if (statements) {
91081                 delete deferredExports[id];
91082                 return ts.append(statements, node);
91083             }
91084             else {
91085                 var original = ts.getOriginalNode(node);
91086                 if (ts.isModuleOrEnumDeclaration(original)) {
91087                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91088                 }
91089             }
91090             return node;
91091         }
91092         /**
91093          * Appends the exports of an ImportDeclaration to a statement list, returning the
91094          * statement list.
91095          *
91096          * @param statements A statement list to which the down-level export statements are to be
91097          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91098          * appended.
91099          * @param decl The declaration whose exports are to be recorded.
91100          */
91101         function appendExportsOfImportDeclaration(statements, decl) {
91102             if (moduleInfo.exportEquals) {
91103                 return statements;
91104             }
91105             var importClause = decl.importClause;
91106             if (!importClause) {
91107                 return statements;
91108             }
91109             if (importClause.name) {
91110                 statements = appendExportsOfDeclaration(statements, importClause);
91111             }
91112             var namedBindings = importClause.namedBindings;
91113             if (namedBindings) {
91114                 switch (namedBindings.kind) {
91115                     case 256 /* NamespaceImport */:
91116                         statements = appendExportsOfDeclaration(statements, namedBindings);
91117                         break;
91118                     case 257 /* NamedImports */:
91119                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91120                             var importBinding = _a[_i];
91121                             statements = appendExportsOfDeclaration(statements, importBinding);
91122                         }
91123                         break;
91124                 }
91125             }
91126             return statements;
91127         }
91128         /**
91129          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91130          * statement list.
91131          *
91132          * @param statements A statement list to which the down-level export statements are to be
91133          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91134          * appended.
91135          * @param decl The declaration whose exports are to be recorded.
91136          */
91137         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91138             if (moduleInfo.exportEquals) {
91139                 return statements;
91140             }
91141             return appendExportsOfDeclaration(statements, decl);
91142         }
91143         /**
91144          * Appends the exports of a VariableStatement to a statement list, returning the statement
91145          * list.
91146          *
91147          * @param statements A statement list to which the down-level export statements are to be
91148          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91149          * appended.
91150          * @param node The VariableStatement whose exports are to be recorded.
91151          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91152          * `nodes` declaration list.
91153          */
91154         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91155             if (moduleInfo.exportEquals) {
91156                 return statements;
91157             }
91158             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91159                 var decl = _a[_i];
91160                 if (decl.initializer || exportSelf) {
91161                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91162                 }
91163             }
91164             return statements;
91165         }
91166         /**
91167          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91168          * returning the statement list.
91169          *
91170          * @param statements A statement list to which the down-level export statements are to be
91171          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91172          * appended.
91173          * @param decl The declaration whose exports are to be recorded.
91174          * @param exportSelf A value indicating whether to also export the declaration itself.
91175          */
91176         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91177             if (moduleInfo.exportEquals) {
91178                 return statements;
91179             }
91180             if (ts.isBindingPattern(decl.name)) {
91181                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91182                     var element = _a[_i];
91183                     if (!ts.isOmittedExpression(element)) {
91184                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91185                     }
91186                 }
91187             }
91188             else if (!ts.isGeneratedIdentifier(decl.name)) {
91189                 var excludeName = void 0;
91190                 if (exportSelf) {
91191                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91192                     excludeName = ts.idText(decl.name);
91193                 }
91194                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91195             }
91196             return statements;
91197         }
91198         /**
91199          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91200          * returning the statement list.
91201          *
91202          * @param statements A statement list to which the down-level export statements are to be
91203          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91204          * appended.
91205          * @param decl The declaration whose exports are to be recorded.
91206          */
91207         function appendExportsOfHoistedDeclaration(statements, decl) {
91208             if (moduleInfo.exportEquals) {
91209                 return statements;
91210             }
91211             var excludeName;
91212             if (ts.hasModifier(decl, 1 /* Export */)) {
91213                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91214                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91215                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91216             }
91217             if (decl.name) {
91218                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91219             }
91220             return statements;
91221         }
91222         /**
91223          * Appends the exports of a declaration to a statement list, returning the statement list.
91224          *
91225          * @param statements A statement list to which the down-level export statements are to be
91226          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91227          * appended.
91228          * @param decl The declaration to export.
91229          * @param excludeName An optional name to exclude from exports.
91230          */
91231         function appendExportsOfDeclaration(statements, decl, excludeName) {
91232             if (moduleInfo.exportEquals) {
91233                 return statements;
91234             }
91235             var name = ts.getDeclarationName(decl);
91236             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91237             if (exportSpecifiers) {
91238                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91239                     var exportSpecifier = exportSpecifiers_2[_i];
91240                     if (exportSpecifier.name.escapedText !== excludeName) {
91241                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91242                     }
91243                 }
91244             }
91245             return statements;
91246         }
91247         /**
91248          * Appends the down-level representation of an export to a statement list, returning the
91249          * statement list.
91250          *
91251          * @param statements A statement list to which the down-level export statements are to be
91252          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91253          * appended.
91254          * @param exportName The name of the export.
91255          * @param expression The expression to export.
91256          * @param allowComments Whether to allow comments on the export.
91257          */
91258         function appendExportStatement(statements, exportName, expression, allowComments) {
91259             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91260             return statements;
91261         }
91262         /**
91263          * Creates a call to the current file's export function to export a value.
91264          *
91265          * @param name The bound name of the export.
91266          * @param value The exported value.
91267          * @param allowComments An optional value indicating whether to emit comments for the statement.
91268          */
91269         function createExportStatement(name, value, allowComments) {
91270             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91271             ts.startOnNewLine(statement);
91272             if (!allowComments) {
91273                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91274             }
91275             return statement;
91276         }
91277         /**
91278          * Creates a call to the current file's export function to export a value.
91279          *
91280          * @param name The bound name of the export.
91281          * @param value The exported value.
91282          */
91283         function createExportExpression(name, value) {
91284             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91285             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91286             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91287         }
91288         //
91289         // Top-Level or Nested Source Element Visitors
91290         //
91291         /**
91292          * Visit nested elements at the top-level of a module.
91293          *
91294          * @param node The node to visit.
91295          */
91296         function nestedElementVisitor(node) {
91297             switch (node.kind) {
91298                 case 225 /* VariableStatement */:
91299                     return visitVariableStatement(node);
91300                 case 244 /* FunctionDeclaration */:
91301                     return visitFunctionDeclaration(node);
91302                 case 245 /* ClassDeclaration */:
91303                     return visitClassDeclaration(node);
91304                 case 230 /* ForStatement */:
91305                     return visitForStatement(node);
91306                 case 231 /* ForInStatement */:
91307                     return visitForInStatement(node);
91308                 case 232 /* ForOfStatement */:
91309                     return visitForOfStatement(node);
91310                 case 228 /* DoStatement */:
91311                     return visitDoStatement(node);
91312                 case 229 /* WhileStatement */:
91313                     return visitWhileStatement(node);
91314                 case 238 /* LabeledStatement */:
91315                     return visitLabeledStatement(node);
91316                 case 236 /* WithStatement */:
91317                     return visitWithStatement(node);
91318                 case 237 /* SwitchStatement */:
91319                     return visitSwitchStatement(node);
91320                 case 251 /* CaseBlock */:
91321                     return visitCaseBlock(node);
91322                 case 277 /* CaseClause */:
91323                     return visitCaseClause(node);
91324                 case 278 /* DefaultClause */:
91325                     return visitDefaultClause(node);
91326                 case 240 /* TryStatement */:
91327                     return visitTryStatement(node);
91328                 case 280 /* CatchClause */:
91329                     return visitCatchClause(node);
91330                 case 223 /* Block */:
91331                     return visitBlock(node);
91332                 case 328 /* MergeDeclarationMarker */:
91333                     return visitMergeDeclarationMarker(node);
91334                 case 329 /* EndOfDeclarationMarker */:
91335                     return visitEndOfDeclarationMarker(node);
91336                 default:
91337                     return destructuringAndImportCallVisitor(node);
91338             }
91339         }
91340         /**
91341          * Visits the body of a ForStatement to hoist declarations.
91342          *
91343          * @param node The node to visit.
91344          */
91345         function visitForStatement(node) {
91346             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91347             enclosingBlockScopedContainer = node;
91348             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));
91349             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91350             return node;
91351         }
91352         /**
91353          * Visits the body of a ForInStatement to hoist declarations.
91354          *
91355          * @param node The node to visit.
91356          */
91357         function visitForInStatement(node) {
91358             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91359             enclosingBlockScopedContainer = node;
91360             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91361             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91362             return node;
91363         }
91364         /**
91365          * Visits the body of a ForOfStatement to hoist declarations.
91366          *
91367          * @param node The node to visit.
91368          */
91369         function visitForOfStatement(node) {
91370             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91371             enclosingBlockScopedContainer = node;
91372             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));
91373             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91374             return node;
91375         }
91376         /**
91377          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91378          * ForOfStatement.
91379          *
91380          * @param node The node to test.
91381          */
91382         function shouldHoistForInitializer(node) {
91383             return ts.isVariableDeclarationList(node)
91384                 && shouldHoistVariableDeclarationList(node);
91385         }
91386         /**
91387          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91388          *
91389          * @param node The node to visit.
91390          */
91391         function visitForInitializer(node) {
91392             if (shouldHoistForInitializer(node)) {
91393                 var expressions = void 0;
91394                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91395                     var variable = _a[_i];
91396                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91397                     if (!variable.initializer) {
91398                         hoistBindingElement(variable);
91399                     }
91400                 }
91401                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91402             }
91403             else {
91404                 return ts.visitEachChild(node, nestedElementVisitor, context);
91405             }
91406         }
91407         /**
91408          * Visits the body of a DoStatement to hoist declarations.
91409          *
91410          * @param node The node to visit.
91411          */
91412         function visitDoStatement(node) {
91413             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91414         }
91415         /**
91416          * Visits the body of a WhileStatement to hoist declarations.
91417          *
91418          * @param node The node to visit.
91419          */
91420         function visitWhileStatement(node) {
91421             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91422         }
91423         /**
91424          * Visits the body of a LabeledStatement to hoist declarations.
91425          *
91426          * @param node The node to visit.
91427          */
91428         function visitLabeledStatement(node) {
91429             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91430         }
91431         /**
91432          * Visits the body of a WithStatement to hoist declarations.
91433          *
91434          * @param node The node to visit.
91435          */
91436         function visitWithStatement(node) {
91437             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91438         }
91439         /**
91440          * Visits the body of a SwitchStatement to hoist declarations.
91441          *
91442          * @param node The node to visit.
91443          */
91444         function visitSwitchStatement(node) {
91445             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91446         }
91447         /**
91448          * Visits the body of a CaseBlock to hoist declarations.
91449          *
91450          * @param node The node to visit.
91451          */
91452         function visitCaseBlock(node) {
91453             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91454             enclosingBlockScopedContainer = node;
91455             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91456             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91457             return node;
91458         }
91459         /**
91460          * Visits the body of a CaseClause to hoist declarations.
91461          *
91462          * @param node The node to visit.
91463          */
91464         function visitCaseClause(node) {
91465             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91466         }
91467         /**
91468          * Visits the body of a DefaultClause to hoist declarations.
91469          *
91470          * @param node The node to visit.
91471          */
91472         function visitDefaultClause(node) {
91473             return ts.visitEachChild(node, nestedElementVisitor, context);
91474         }
91475         /**
91476          * Visits the body of a TryStatement to hoist declarations.
91477          *
91478          * @param node The node to visit.
91479          */
91480         function visitTryStatement(node) {
91481             return ts.visitEachChild(node, nestedElementVisitor, context);
91482         }
91483         /**
91484          * Visits the body of a CatchClause to hoist declarations.
91485          *
91486          * @param node The node to visit.
91487          */
91488         function visitCatchClause(node) {
91489             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91490             enclosingBlockScopedContainer = node;
91491             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91492             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91493             return node;
91494         }
91495         /**
91496          * Visits the body of a Block to hoist declarations.
91497          *
91498          * @param node The node to visit.
91499          */
91500         function visitBlock(node) {
91501             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91502             enclosingBlockScopedContainer = node;
91503             node = ts.visitEachChild(node, nestedElementVisitor, context);
91504             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91505             return node;
91506         }
91507         //
91508         // Destructuring Assignment Visitors
91509         //
91510         /**
91511          * Visit nodes to flatten destructuring assignments to exported symbols.
91512          *
91513          * @param node The node to visit.
91514          */
91515         function destructuringAndImportCallVisitor(node) {
91516             if (ts.isDestructuringAssignment(node)) {
91517                 return visitDestructuringAssignment(node);
91518             }
91519             else if (ts.isImportCall(node)) {
91520                 return visitImportCallExpression(node);
91521             }
91522             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91523                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91524             }
91525             else {
91526                 return node;
91527             }
91528         }
91529         function visitImportCallExpression(node) {
91530             // import("./blah")
91531             // emit as
91532             // System.register([], function (_export, _context) {
91533             //     return {
91534             //         setters: [],
91535             //         execute: () => {
91536             //             _context.import('./blah');
91537             //         }
91538             //     };
91539             // });
91540             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91541             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91542         }
91543         /**
91544          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91545          *
91546          * @param node The node to visit.
91547          */
91548         function visitDestructuringAssignment(node) {
91549             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91550                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91551                 /*needsValue*/ true);
91552             }
91553             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91554         }
91555         /**
91556          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91557          *
91558          * @param node The destructuring target.
91559          */
91560         function hasExportedReferenceInDestructuringTarget(node) {
91561             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91562                 return hasExportedReferenceInDestructuringTarget(node.left);
91563             }
91564             else if (ts.isSpreadElement(node)) {
91565                 return hasExportedReferenceInDestructuringTarget(node.expression);
91566             }
91567             else if (ts.isObjectLiteralExpression(node)) {
91568                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91569             }
91570             else if (ts.isArrayLiteralExpression(node)) {
91571                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91572             }
91573             else if (ts.isShorthandPropertyAssignment(node)) {
91574                 return hasExportedReferenceInDestructuringTarget(node.name);
91575             }
91576             else if (ts.isPropertyAssignment(node)) {
91577                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91578             }
91579             else if (ts.isIdentifier(node)) {
91580                 var container = resolver.getReferencedExportContainer(node);
91581                 return container !== undefined && container.kind === 290 /* SourceFile */;
91582             }
91583             else {
91584                 return false;
91585             }
91586         }
91587         //
91588         // Modifier Visitors
91589         //
91590         /**
91591          * Visit nodes to elide module-specific modifiers.
91592          *
91593          * @param node The node to visit.
91594          */
91595         function modifierVisitor(node) {
91596             switch (node.kind) {
91597                 case 89 /* ExportKeyword */:
91598                 case 84 /* DefaultKeyword */:
91599                     return undefined;
91600             }
91601             return node;
91602         }
91603         //
91604         // Emit Notification
91605         //
91606         /**
91607          * Hook for node emit notifications.
91608          *
91609          * @param hint A hint as to the intended usage of the node.
91610          * @param node The node to emit.
91611          * @param emitCallback A callback used to emit the node in the printer.
91612          */
91613         function onEmitNode(hint, node, emitCallback) {
91614             if (node.kind === 290 /* SourceFile */) {
91615                 var id = ts.getOriginalNodeId(node);
91616                 currentSourceFile = node;
91617                 moduleInfo = moduleInfoMap[id];
91618                 exportFunction = exportFunctionsMap[id];
91619                 noSubstitution = noSubstitutionMap[id];
91620                 contextObject = contextObjectMap[id];
91621                 if (noSubstitution) {
91622                     delete noSubstitutionMap[id];
91623                 }
91624                 previousOnEmitNode(hint, node, emitCallback);
91625                 currentSourceFile = undefined;
91626                 moduleInfo = undefined;
91627                 exportFunction = undefined;
91628                 contextObject = undefined;
91629                 noSubstitution = undefined;
91630             }
91631             else {
91632                 previousOnEmitNode(hint, node, emitCallback);
91633             }
91634         }
91635         //
91636         // Substitutions
91637         //
91638         /**
91639          * Hooks node substitutions.
91640          *
91641          * @param hint A hint as to the intended usage of the node.
91642          * @param node The node to substitute.
91643          */
91644         function onSubstituteNode(hint, node) {
91645             node = previousOnSubstituteNode(hint, node);
91646             if (isSubstitutionPrevented(node)) {
91647                 return node;
91648             }
91649             if (hint === 1 /* Expression */) {
91650                 return substituteExpression(node);
91651             }
91652             else if (hint === 4 /* Unspecified */) {
91653                 return substituteUnspecified(node);
91654             }
91655             return node;
91656         }
91657         /**
91658          * Substitute the node, if necessary.
91659          *
91660          * @param node The node to substitute.
91661          */
91662         function substituteUnspecified(node) {
91663             switch (node.kind) {
91664                 case 282 /* ShorthandPropertyAssignment */:
91665                     return substituteShorthandPropertyAssignment(node);
91666             }
91667             return node;
91668         }
91669         /**
91670          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91671          *
91672          * @param node The node to substitute.
91673          */
91674         function substituteShorthandPropertyAssignment(node) {
91675             var name = node.name;
91676             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91677                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91678                 if (importDeclaration) {
91679                     if (ts.isImportClause(importDeclaration)) {
91680                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91681                         /*location*/ node);
91682                     }
91683                     else if (ts.isImportSpecifier(importDeclaration)) {
91684                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91685                         /*location*/ node);
91686                     }
91687                 }
91688             }
91689             return node;
91690         }
91691         /**
91692          * Substitute the expression, if necessary.
91693          *
91694          * @param node The node to substitute.
91695          */
91696         function substituteExpression(node) {
91697             switch (node.kind) {
91698                 case 75 /* Identifier */:
91699                     return substituteExpressionIdentifier(node);
91700                 case 209 /* BinaryExpression */:
91701                     return substituteBinaryExpression(node);
91702                 case 207 /* PrefixUnaryExpression */:
91703                 case 208 /* PostfixUnaryExpression */:
91704                     return substituteUnaryExpression(node);
91705                 case 219 /* MetaProperty */:
91706                     return substituteMetaProperty(node);
91707             }
91708             return node;
91709         }
91710         /**
91711          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91712          *
91713          * @param node The node to substitute.
91714          */
91715         function substituteExpressionIdentifier(node) {
91716             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91717                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91718                 if (externalHelpersModuleName) {
91719                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91720                 }
91721                 return node;
91722             }
91723             // When we see an identifier in an expression position that
91724             // points to an imported symbol, we should substitute a qualified
91725             // reference to the imported symbol if one is needed.
91726             //
91727             // - We do not substitute generated identifiers for any reason.
91728             // - We do not substitute identifiers tagged with the LocalName flag.
91729             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91730                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91731                 if (importDeclaration) {
91732                     if (ts.isImportClause(importDeclaration)) {
91733                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91734                         /*location*/ node);
91735                     }
91736                     else if (ts.isImportSpecifier(importDeclaration)) {
91737                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91738                         /*location*/ node);
91739                     }
91740                 }
91741             }
91742             return node;
91743         }
91744         /**
91745          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91746          *
91747          * @param node The node to substitute.
91748          */
91749         function substituteBinaryExpression(node) {
91750             // When we see an assignment expression whose left-hand side is an exported symbol,
91751             // we should ensure all exports of that symbol are updated with the correct value.
91752             //
91753             // - We do not substitute generated identifiers for any reason.
91754             // - We do not substitute identifiers tagged with the LocalName flag.
91755             // - We do not substitute identifiers that were originally the name of an enum or
91756             //   namespace due to how they are transformed in TypeScript.
91757             // - We only substitute identifiers that are exported at the top level.
91758             if (ts.isAssignmentOperator(node.operatorToken.kind)
91759                 && ts.isIdentifier(node.left)
91760                 && !ts.isGeneratedIdentifier(node.left)
91761                 && !ts.isLocalName(node.left)
91762                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91763                 var exportedNames = getExports(node.left);
91764                 if (exportedNames) {
91765                     // For each additional export of the declaration, apply an export assignment.
91766                     var expression = node;
91767                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91768                         var exportName = exportedNames_4[_i];
91769                         expression = createExportExpression(exportName, preventSubstitution(expression));
91770                     }
91771                     return expression;
91772                 }
91773             }
91774             return node;
91775         }
91776         /**
91777          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91778          *
91779          * @param node The node to substitute.
91780          */
91781         function substituteUnaryExpression(node) {
91782             // When we see a prefix or postfix increment expression whose operand is an exported
91783             // symbol, we should ensure all exports of that symbol are updated with the correct
91784             // value.
91785             //
91786             // - We do not substitute generated identifiers for any reason.
91787             // - We do not substitute identifiers tagged with the LocalName flag.
91788             // - We do not substitute identifiers that were originally the name of an enum or
91789             //   namespace due to how they are transformed in TypeScript.
91790             // - We only substitute identifiers that are exported at the top level.
91791             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91792                 && ts.isIdentifier(node.operand)
91793                 && !ts.isGeneratedIdentifier(node.operand)
91794                 && !ts.isLocalName(node.operand)
91795                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91796                 var exportedNames = getExports(node.operand);
91797                 if (exportedNames) {
91798                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91799                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91800                         : node;
91801                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91802                         var exportName = exportedNames_5[_i];
91803                         expression = createExportExpression(exportName, preventSubstitution(expression));
91804                     }
91805                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91806                         expression = node.operator === 45 /* PlusPlusToken */
91807                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91808                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91809                     }
91810                     return expression;
91811                 }
91812             }
91813             return node;
91814         }
91815         function substituteMetaProperty(node) {
91816             if (ts.isImportMeta(node)) {
91817                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
91818             }
91819             return node;
91820         }
91821         /**
91822          * Gets the exports of a name.
91823          *
91824          * @param name The name.
91825          */
91826         function getExports(name) {
91827             var exportedNames;
91828             if (!ts.isGeneratedIdentifier(name)) {
91829                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
91830                     || resolver.getReferencedValueDeclaration(name);
91831                 if (valueDeclaration) {
91832                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
91833                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
91834                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
91835                     }
91836                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
91837                 }
91838             }
91839             return exportedNames;
91840         }
91841         /**
91842          * Prevent substitution of a node for this transformer.
91843          *
91844          * @param node The node which should not be substituted.
91845          */
91846         function preventSubstitution(node) {
91847             if (noSubstitution === undefined)
91848                 noSubstitution = [];
91849             noSubstitution[ts.getNodeId(node)] = true;
91850             return node;
91851         }
91852         /**
91853          * Determines whether a node should not be substituted.
91854          *
91855          * @param node The node to test.
91856          */
91857         function isSubstitutionPrevented(node) {
91858             return noSubstitution && node.id && noSubstitution[node.id];
91859         }
91860     }
91861     ts.transformSystemModule = transformSystemModule;
91862 })(ts || (ts = {}));
91863 /*@internal*/
91864 var ts;
91865 (function (ts) {
91866     function transformECMAScriptModule(context) {
91867         var compilerOptions = context.getCompilerOptions();
91868         var previousOnEmitNode = context.onEmitNode;
91869         var previousOnSubstituteNode = context.onSubstituteNode;
91870         context.onEmitNode = onEmitNode;
91871         context.onSubstituteNode = onSubstituteNode;
91872         context.enableEmitNotification(290 /* SourceFile */);
91873         context.enableSubstitution(75 /* Identifier */);
91874         var helperNameSubstitutions;
91875         return ts.chainBundle(transformSourceFile);
91876         function transformSourceFile(node) {
91877             if (node.isDeclarationFile) {
91878                 return node;
91879             }
91880             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
91881                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
91882                 if (externalHelpersImportDeclaration) {
91883                     var statements = [];
91884                     var statementOffset = ts.addPrologue(statements, node.statements);
91885                     ts.append(statements, externalHelpersImportDeclaration);
91886                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
91887                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
91888                 }
91889                 else {
91890                     return ts.visitEachChild(node, visitor, context);
91891                 }
91892             }
91893             return node;
91894         }
91895         function visitor(node) {
91896             switch (node.kind) {
91897                 case 253 /* ImportEqualsDeclaration */:
91898                     // Elide `import=` as it is not legal with --module ES6
91899                     return undefined;
91900                 case 259 /* ExportAssignment */:
91901                     return visitExportAssignment(node);
91902                 case 260 /* ExportDeclaration */:
91903                     var exportDecl = node;
91904                     return visitExportDeclaration(exportDecl);
91905             }
91906             return node;
91907         }
91908         function visitExportAssignment(node) {
91909             // Elide `export=` as it is not legal with --module ES6
91910             return node.isExportEquals ? undefined : node;
91911         }
91912         function visitExportDeclaration(node) {
91913             // `export * as ns` only needs to be transformed in ES2015
91914             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
91915                 return node;
91916             }
91917             // Either ill-formed or don't need to be tranformed.
91918             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
91919                 return node;
91920             }
91921             var oldIdentifier = node.exportClause.name;
91922             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
91923             var importDecl = ts.createImportDeclaration(
91924             /*decorators*/ undefined, 
91925             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
91926             ts.setOriginalNode(importDecl, node.exportClause);
91927             var exportDecl = ts.createExportDeclaration(
91928             /*decorators*/ undefined, 
91929             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
91930             ts.setOriginalNode(exportDecl, node);
91931             return [importDecl, exportDecl];
91932         }
91933         //
91934         // Emit Notification
91935         //
91936         /**
91937          * Hook for node emit.
91938          *
91939          * @param hint A hint as to the intended usage of the node.
91940          * @param node The node to emit.
91941          * @param emit A callback used to emit the node in the printer.
91942          */
91943         function onEmitNode(hint, node, emitCallback) {
91944             if (ts.isSourceFile(node)) {
91945                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
91946                     helperNameSubstitutions = ts.createMap();
91947                 }
91948                 previousOnEmitNode(hint, node, emitCallback);
91949                 helperNameSubstitutions = undefined;
91950             }
91951             else {
91952                 previousOnEmitNode(hint, node, emitCallback);
91953             }
91954         }
91955         //
91956         // Substitutions
91957         //
91958         /**
91959          * Hooks node substitutions.
91960          *
91961          * @param hint A hint as to the intended usage of the node.
91962          * @param node The node to substitute.
91963          */
91964         function onSubstituteNode(hint, node) {
91965             node = previousOnSubstituteNode(hint, node);
91966             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
91967                 return substituteHelperName(node);
91968             }
91969             return node;
91970         }
91971         function substituteHelperName(node) {
91972             var name = ts.idText(node);
91973             var substitution = helperNameSubstitutions.get(name);
91974             if (!substitution) {
91975                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
91976             }
91977             return substitution;
91978         }
91979     }
91980     ts.transformECMAScriptModule = transformECMAScriptModule;
91981 })(ts || (ts = {}));
91982 /* @internal */
91983 var ts;
91984 (function (ts) {
91985     function canProduceDiagnostics(node) {
91986         return ts.isVariableDeclaration(node) ||
91987             ts.isPropertyDeclaration(node) ||
91988             ts.isPropertySignature(node) ||
91989             ts.isBindingElement(node) ||
91990             ts.isSetAccessor(node) ||
91991             ts.isGetAccessor(node) ||
91992             ts.isConstructSignatureDeclaration(node) ||
91993             ts.isCallSignatureDeclaration(node) ||
91994             ts.isMethodDeclaration(node) ||
91995             ts.isMethodSignature(node) ||
91996             ts.isFunctionDeclaration(node) ||
91997             ts.isParameter(node) ||
91998             ts.isTypeParameterDeclaration(node) ||
91999             ts.isExpressionWithTypeArguments(node) ||
92000             ts.isImportEqualsDeclaration(node) ||
92001             ts.isTypeAliasDeclaration(node) ||
92002             ts.isConstructorDeclaration(node) ||
92003             ts.isIndexSignatureDeclaration(node) ||
92004             ts.isPropertyAccessExpression(node);
92005     }
92006     ts.canProduceDiagnostics = canProduceDiagnostics;
92007     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92008         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92009             return getAccessorNameVisibilityError;
92010         }
92011         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92012             return getMethodNameVisibilityError;
92013         }
92014         else {
92015             return createGetSymbolAccessibilityDiagnosticForNode(node);
92016         }
92017         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92018             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92019             return diagnosticMessage !== undefined ? {
92020                 diagnosticMessage: diagnosticMessage,
92021                 errorNode: node,
92022                 typeName: node.name
92023             } : undefined;
92024         }
92025         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92026             if (ts.hasModifier(node, 32 /* Static */)) {
92027                 return symbolAccessibilityResult.errorModuleName ?
92028                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92029                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92030                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92031                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92032             }
92033             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92034                 return symbolAccessibilityResult.errorModuleName ?
92035                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92036                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92037                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92038                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92039             }
92040             else {
92041                 return symbolAccessibilityResult.errorModuleName ?
92042                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92043                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92044             }
92045         }
92046         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92047             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92048             return diagnosticMessage !== undefined ? {
92049                 diagnosticMessage: diagnosticMessage,
92050                 errorNode: node,
92051                 typeName: node.name
92052             } : undefined;
92053         }
92054         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92055             if (ts.hasModifier(node, 32 /* Static */)) {
92056                 return symbolAccessibilityResult.errorModuleName ?
92057                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92058                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92059                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92060                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92061             }
92062             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92063                 return symbolAccessibilityResult.errorModuleName ?
92064                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92065                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92066                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92067                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92068             }
92069             else {
92070                 return symbolAccessibilityResult.errorModuleName ?
92071                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92072                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92073             }
92074         }
92075     }
92076     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92077     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92078         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92079             return getVariableDeclarationTypeVisibilityError;
92080         }
92081         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92082             return getAccessorDeclarationTypeVisibilityError;
92083         }
92084         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92085             return getReturnTypeVisibilityError;
92086         }
92087         else if (ts.isParameter(node)) {
92088             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92089                 return getVariableDeclarationTypeVisibilityError;
92090             }
92091             return getParameterDeclarationTypeVisibilityError;
92092         }
92093         else if (ts.isTypeParameterDeclaration(node)) {
92094             return getTypeParameterConstraintVisibilityError;
92095         }
92096         else if (ts.isExpressionWithTypeArguments(node)) {
92097             return getHeritageClauseVisibilityError;
92098         }
92099         else if (ts.isImportEqualsDeclaration(node)) {
92100             return getImportEntityNameVisibilityError;
92101         }
92102         else if (ts.isTypeAliasDeclaration(node)) {
92103             return getTypeAliasDeclarationVisibilityError;
92104         }
92105         else {
92106             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92107         }
92108         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92109             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92110                 return symbolAccessibilityResult.errorModuleName ?
92111                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92112                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92113                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92114                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92115             }
92116             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92117             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92118             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92119                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92120                 // TODO(jfreeman): Deal with computed properties in error reporting.
92121                 if (ts.hasModifier(node, 32 /* Static */)) {
92122                     return symbolAccessibilityResult.errorModuleName ?
92123                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92124                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92125                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92126                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92127                 }
92128                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92129                     return symbolAccessibilityResult.errorModuleName ?
92130                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92131                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92132                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92133                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92134                 }
92135                 else {
92136                     // Interfaces cannot have types that cannot be named
92137                     return symbolAccessibilityResult.errorModuleName ?
92138                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92139                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92140                 }
92141             }
92142         }
92143         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92144             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92145             return diagnosticMessage !== undefined ? {
92146                 diagnosticMessage: diagnosticMessage,
92147                 errorNode: node,
92148                 typeName: node.name
92149             } : undefined;
92150         }
92151         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92152             var diagnosticMessage;
92153             if (node.kind === 164 /* SetAccessor */) {
92154                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92155                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92156                 if (ts.hasModifier(node, 32 /* Static */)) {
92157                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92158                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92159                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92160                 }
92161                 else {
92162                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92163                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92164                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92165                 }
92166             }
92167             else {
92168                 if (ts.hasModifier(node, 32 /* Static */)) {
92169                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92170                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92171                             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 :
92172                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92173                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92174                 }
92175                 else {
92176                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92177                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92178                             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 :
92179                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92180                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92181                 }
92182             }
92183             return {
92184                 diagnosticMessage: diagnosticMessage,
92185                 errorNode: node.name,
92186                 typeName: node.name
92187             };
92188         }
92189         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92190             var diagnosticMessage;
92191             switch (node.kind) {
92192                 case 166 /* ConstructSignature */:
92193                     // Interfaces cannot have return types that cannot be named
92194                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92195                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92196                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92197                     break;
92198                 case 165 /* CallSignature */:
92199                     // Interfaces cannot have return types that cannot be named
92200                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92201                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92202                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92203                     break;
92204                 case 167 /* IndexSignature */:
92205                     // Interfaces cannot have return types that cannot be named
92206                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92207                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92208                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92209                     break;
92210                 case 161 /* MethodDeclaration */:
92211                 case 160 /* MethodSignature */:
92212                     if (ts.hasModifier(node, 32 /* Static */)) {
92213                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92214                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92215                                 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 :
92216                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92217                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92218                     }
92219                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92220                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92221                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92222                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92223                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92224                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92225                     }
92226                     else {
92227                         // Interfaces cannot have return types that cannot be named
92228                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92229                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92230                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92231                     }
92232                     break;
92233                 case 244 /* FunctionDeclaration */:
92234                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92235                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92236                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92237                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92238                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92239                     break;
92240                 default:
92241                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92242             }
92243             return {
92244                 diagnosticMessage: diagnosticMessage,
92245                 errorNode: node.name || node
92246             };
92247         }
92248         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92249             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92250             return diagnosticMessage !== undefined ? {
92251                 diagnosticMessage: diagnosticMessage,
92252                 errorNode: node,
92253                 typeName: node.name
92254             } : undefined;
92255         }
92256         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92257             switch (node.parent.kind) {
92258                 case 162 /* Constructor */:
92259                     return symbolAccessibilityResult.errorModuleName ?
92260                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92261                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92262                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92263                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92264                 case 166 /* ConstructSignature */:
92265                 case 171 /* ConstructorType */:
92266                     // Interfaces cannot have parameter types that cannot be named
92267                     return symbolAccessibilityResult.errorModuleName ?
92268                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92269                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92270                 case 165 /* CallSignature */:
92271                     // Interfaces cannot have parameter types that cannot be named
92272                     return symbolAccessibilityResult.errorModuleName ?
92273                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92274                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92275                 case 167 /* IndexSignature */:
92276                     // Interfaces cannot have parameter types that cannot be named
92277                     return symbolAccessibilityResult.errorModuleName ?
92278                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92279                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92280                 case 161 /* MethodDeclaration */:
92281                 case 160 /* MethodSignature */:
92282                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92283                         return symbolAccessibilityResult.errorModuleName ?
92284                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92285                                 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 :
92286                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92287                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92288                     }
92289                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92290                         return symbolAccessibilityResult.errorModuleName ?
92291                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92292                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92293                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92294                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92295                     }
92296                     else {
92297                         // Interfaces cannot have parameter types that cannot be named
92298                         return symbolAccessibilityResult.errorModuleName ?
92299                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92300                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92301                     }
92302                 case 244 /* FunctionDeclaration */:
92303                 case 170 /* FunctionType */:
92304                     return symbolAccessibilityResult.errorModuleName ?
92305                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92306                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92307                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92308                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92309                 case 164 /* SetAccessor */:
92310                 case 163 /* GetAccessor */:
92311                     return symbolAccessibilityResult.errorModuleName ?
92312                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92313                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92314                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92315                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92316                 default:
92317                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92318             }
92319         }
92320         function getTypeParameterConstraintVisibilityError() {
92321             // Type parameter constraints are named by user so we should always be able to name it
92322             var diagnosticMessage;
92323             switch (node.parent.kind) {
92324                 case 245 /* ClassDeclaration */:
92325                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92326                     break;
92327                 case 246 /* InterfaceDeclaration */:
92328                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92329                     break;
92330                 case 186 /* MappedType */:
92331                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92332                     break;
92333                 case 171 /* ConstructorType */:
92334                 case 166 /* ConstructSignature */:
92335                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92336                     break;
92337                 case 165 /* CallSignature */:
92338                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92339                     break;
92340                 case 161 /* MethodDeclaration */:
92341                 case 160 /* MethodSignature */:
92342                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92343                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92344                     }
92345                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92346                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92347                     }
92348                     else {
92349                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92350                     }
92351                     break;
92352                 case 170 /* FunctionType */:
92353                 case 244 /* FunctionDeclaration */:
92354                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92355                     break;
92356                 case 247 /* TypeAliasDeclaration */:
92357                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92358                     break;
92359                 default:
92360                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92361             }
92362             return {
92363                 diagnosticMessage: diagnosticMessage,
92364                 errorNode: node,
92365                 typeName: node.name
92366             };
92367         }
92368         function getHeritageClauseVisibilityError() {
92369             var diagnosticMessage;
92370             // Heritage clause is written by user so it can always be named
92371             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92372                 // Class or Interface implemented/extended is inaccessible
92373                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92374                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92375                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92376             }
92377             else {
92378                 // interface is inaccessible
92379                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92380             }
92381             return {
92382                 diagnosticMessage: diagnosticMessage,
92383                 errorNode: node,
92384                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92385             };
92386         }
92387         function getImportEntityNameVisibilityError() {
92388             return {
92389                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92390                 errorNode: node,
92391                 typeName: node.name
92392             };
92393         }
92394         function getTypeAliasDeclarationVisibilityError() {
92395             return {
92396                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92397                 errorNode: node.type,
92398                 typeName: node.name
92399             };
92400         }
92401     }
92402     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92403 })(ts || (ts = {}));
92404 /*@internal*/
92405 var ts;
92406 (function (ts) {
92407     function getDeclarationDiagnostics(host, resolver, file) {
92408         if (file && ts.isJsonSourceFile(file)) {
92409             return []; // No declaration diagnostics for json for now
92410         }
92411         var compilerOptions = host.getCompilerOptions();
92412         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92413         return result.diagnostics;
92414     }
92415     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92416     function hasInternalAnnotation(range, currentSourceFile) {
92417         var comment = currentSourceFile.text.substring(range.pos, range.end);
92418         return ts.stringContains(comment, "@internal");
92419     }
92420     function isInternalDeclaration(node, currentSourceFile) {
92421         var parseTreeNode = ts.getParseTreeNode(node);
92422         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92423             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92424             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92425             var text = currentSourceFile.text;
92426             var commentRanges = previousSibling
92427                 ? ts.concatenate(
92428                 // to handle
92429                 // ... parameters, /* @internal */
92430                 // public param: string
92431                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92432                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92433             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92434         }
92435         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92436         return !!ts.forEach(leadingCommentRanges, function (range) {
92437             return hasInternalAnnotation(range, currentSourceFile);
92438         });
92439     }
92440     ts.isInternalDeclaration = isInternalDeclaration;
92441     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92442         2048 /* WriteClassExpressionAsTypeLiteral */ |
92443         4096 /* UseTypeOfFunction */ |
92444         8 /* UseStructuralFallback */ |
92445         524288 /* AllowEmptyTuple */ |
92446         4 /* GenerateNamesForShadowedTypeParams */ |
92447         1 /* NoTruncation */;
92448     /**
92449      * Transforms a ts file into a .d.ts file
92450      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92451      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92452      * This means that _no transforms should be allowed to occur before this one_.
92453      */
92454     function transformDeclarations(context) {
92455         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92456         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92457         var needsDeclare = true;
92458         var isBundledEmit = false;
92459         var resultHasExternalModuleIndicator = false;
92460         var needsScopeFixMarker = false;
92461         var resultHasScopeMarker = false;
92462         var enclosingDeclaration;
92463         var necessaryTypeReferences;
92464         var lateMarkedStatements;
92465         var lateStatementReplacementMap;
92466         var suppressNewDiagnosticContexts;
92467         var exportedModulesFromDeclarationEmit;
92468         var host = context.getEmitHost();
92469         var symbolTracker = {
92470             trackSymbol: trackSymbol,
92471             reportInaccessibleThisError: reportInaccessibleThisError,
92472             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92473             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92474             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92475             moduleResolverHost: host,
92476             trackReferencedAmbientModule: trackReferencedAmbientModule,
92477             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92478             reportNonlocalAugmentation: reportNonlocalAugmentation
92479         };
92480         var errorNameNode;
92481         var currentSourceFile;
92482         var refs;
92483         var libs;
92484         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92485         var resolver = context.getEmitResolver();
92486         var options = context.getCompilerOptions();
92487         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92488         return transformRoot;
92489         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92490             if (!typeReferenceDirectives) {
92491                 return;
92492             }
92493             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92494             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92495                 var ref = typeReferenceDirectives_2[_i];
92496                 necessaryTypeReferences.set(ref, true);
92497             }
92498         }
92499         function trackReferencedAmbientModule(node, symbol) {
92500             // If it is visible via `// <reference types="..."/>`, then we should just use that
92501             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92502             if (ts.length(directives)) {
92503                 return recordTypeReferenceDirectivesIfNecessary(directives);
92504             }
92505             // Otherwise we should emit a path-based reference
92506             var container = ts.getSourceFileOfNode(node);
92507             refs.set("" + ts.getOriginalNodeId(container), container);
92508         }
92509         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92510             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92511                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92512                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92513                     if (!lateMarkedStatements) {
92514                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92515                     }
92516                     else {
92517                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92518                             var ref = _a[_i];
92519                             ts.pushIfUnique(lateMarkedStatements, ref);
92520                         }
92521                     }
92522                 }
92523                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92524             }
92525             else {
92526                 // Report error
92527                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92528                 if (errorInfo) {
92529                     if (errorInfo.typeName) {
92530                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92531                     }
92532                     else {
92533                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92534                     }
92535                 }
92536             }
92537         }
92538         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92539             if (!isBundledEmit) {
92540                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92541             }
92542         }
92543         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92544             if (symbol.flags & 262144 /* TypeParameter */)
92545                 return;
92546             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92547             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92548         }
92549         function reportPrivateInBaseOfClassExpression(propertyName) {
92550             if (errorNameNode) {
92551                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92552             }
92553         }
92554         function reportInaccessibleUniqueSymbolError() {
92555             if (errorNameNode) {
92556                 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"));
92557             }
92558         }
92559         function reportInaccessibleThisError() {
92560             if (errorNameNode) {
92561                 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"));
92562             }
92563         }
92564         function reportLikelyUnsafeImportRequiredError(specifier) {
92565             if (errorNameNode) {
92566                 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));
92567             }
92568         }
92569         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92570             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92571             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92572             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92573                 var augmentations = augmentingDeclarations_1[_i];
92574                 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)));
92575             }
92576         }
92577         function transformDeclarationsForJS(sourceFile, bundled) {
92578             var oldDiag = getSymbolAccessibilityDiagnostic;
92579             getSymbolAccessibilityDiagnostic = function (s) { return ({
92580                 diagnosticMessage: s.errorModuleName
92581                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92582                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92583                 errorNode: s.errorNode || sourceFile
92584             }); };
92585             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92586             getSymbolAccessibilityDiagnostic = oldDiag;
92587             return result;
92588         }
92589         function transformRoot(node) {
92590             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92591                 return node;
92592             }
92593             if (node.kind === 291 /* Bundle */) {
92594                 isBundledEmit = true;
92595                 refs = ts.createMap();
92596                 libs = ts.createMap();
92597                 var hasNoDefaultLib_1 = false;
92598                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92599                     if (sourceFile.isDeclarationFile)
92600                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92601                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92602                     currentSourceFile = sourceFile;
92603                     enclosingDeclaration = sourceFile;
92604                     lateMarkedStatements = undefined;
92605                     suppressNewDiagnosticContexts = false;
92606                     lateStatementReplacementMap = ts.createMap();
92607                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92608                     needsScopeFixMarker = false;
92609                     resultHasScopeMarker = false;
92610                     collectReferences(sourceFile, refs);
92611                     collectLibs(sourceFile, libs);
92612                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92613                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92614                         needsDeclare = false;
92615                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92616                         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*/ []);
92617                         return newFile;
92618                     }
92619                     needsDeclare = true;
92620                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92621                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92622                 }), ts.mapDefined(node.prepends, function (prepend) {
92623                     if (prepend.kind === 293 /* InputFiles */) {
92624                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92625                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92626                         collectReferences(sourceFile, refs);
92627                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92628                         collectLibs(sourceFile, libs);
92629                         return sourceFile;
92630                     }
92631                     return prepend;
92632                 }));
92633                 bundle.syntheticFileReferences = [];
92634                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92635                 bundle.syntheticLibReferences = getLibReferences();
92636                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92637                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92638                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92639                 refs.forEach(referenceVisitor_1);
92640                 return bundle;
92641             }
92642             // Single source file
92643             needsDeclare = true;
92644             needsScopeFixMarker = false;
92645             resultHasScopeMarker = false;
92646             enclosingDeclaration = node;
92647             currentSourceFile = node;
92648             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92649             isBundledEmit = false;
92650             resultHasExternalModuleIndicator = false;
92651             suppressNewDiagnosticContexts = false;
92652             lateMarkedStatements = undefined;
92653             lateStatementReplacementMap = ts.createMap();
92654             necessaryTypeReferences = undefined;
92655             refs = collectReferences(currentSourceFile, ts.createMap());
92656             libs = collectLibs(currentSourceFile, ts.createMap());
92657             var references = [];
92658             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92659             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92660             var combinedStatements;
92661             if (ts.isSourceFileJS(currentSourceFile)) {
92662                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92663                 refs.forEach(referenceVisitor);
92664                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92665             }
92666             else {
92667                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92668                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92669                 refs.forEach(referenceVisitor);
92670                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92671                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92672                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92673                 }
92674             }
92675             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92676             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92677             return updated;
92678             function getLibReferences() {
92679                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92680             }
92681             function getFileReferencesForUsedTypeReferences() {
92682                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92683             }
92684             function getFileReferenceForTypeName(typeName) {
92685                 // Elide type references for which we have imports
92686                 if (emittedImports) {
92687                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92688                         var importStatement = emittedImports_1[_i];
92689                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92690                             var expr = importStatement.moduleReference.expression;
92691                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92692                                 return undefined;
92693                             }
92694                         }
92695                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92696                             return undefined;
92697                         }
92698                     }
92699                 }
92700                 return { fileName: typeName, pos: -1, end: -1 };
92701             }
92702             function mapReferencesIntoArray(references, outputFilePath) {
92703                 return function (file) {
92704                     var declFileName;
92705                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92706                         declFileName = file.fileName;
92707                     }
92708                     else {
92709                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92710                             return; // Omit references to files which are being merged
92711                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92712                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92713                     }
92714                     if (declFileName) {
92715                         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, 
92716                         /*preferences*/ undefined);
92717                         if (!ts.pathIsRelative(specifier)) {
92718                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92719                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92720                             // a relative path to the declaration file
92721                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92722                             return;
92723                         }
92724                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92725                         /*isAbsolutePathAnUrl*/ false);
92726                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92727                             fileName = fileName.substring(2);
92728                         }
92729                         // omit references to files from node_modules (npm may disambiguate module
92730                         // references when installing this package, making the path is unreliable).
92731                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92732                             return;
92733                         }
92734                         references.push({ pos: -1, end: -1, fileName: fileName });
92735                     }
92736                 };
92737             }
92738         }
92739         function collectReferences(sourceFile, ret) {
92740             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92741                 return ret;
92742             ts.forEach(sourceFile.referencedFiles, function (f) {
92743                 var elem = host.getSourceFileFromReference(sourceFile, f);
92744                 if (elem) {
92745                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92746                 }
92747             });
92748             return ret;
92749         }
92750         function collectLibs(sourceFile, ret) {
92751             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92752                 var lib = host.getLibFileFromReference(ref);
92753                 if (lib) {
92754                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92755                 }
92756             });
92757             return ret;
92758         }
92759         function filterBindingPatternInitializers(name) {
92760             if (name.kind === 75 /* Identifier */) {
92761                 return name;
92762             }
92763             else {
92764                 if (name.kind === 190 /* ArrayBindingPattern */) {
92765                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92766                 }
92767                 else {
92768                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92769                 }
92770             }
92771             function visitBindingElement(elem) {
92772                 if (elem.kind === 215 /* OmittedExpression */) {
92773                     return elem;
92774                 }
92775                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92776             }
92777         }
92778         function ensureParameter(p, modifierMask, type) {
92779             var oldDiag;
92780             if (!suppressNewDiagnosticContexts) {
92781                 oldDiag = getSymbolAccessibilityDiagnostic;
92782                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92783             }
92784             var newParam = ts.updateParameter(p, 
92785             /*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
92786             ensureNoInitializer(p));
92787             if (!suppressNewDiagnosticContexts) {
92788                 getSymbolAccessibilityDiagnostic = oldDiag;
92789             }
92790             return newParam;
92791         }
92792         function shouldPrintWithInitializer(node) {
92793             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92794         }
92795         function ensureNoInitializer(node) {
92796             if (shouldPrintWithInitializer(node)) {
92797                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92798             }
92799             return undefined;
92800         }
92801         function ensureType(node, type, ignorePrivate) {
92802             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92803                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92804                 return;
92805             }
92806             if (shouldPrintWithInitializer(node)) {
92807                 // Literal const declarations will have an initializer ensured rather than a type
92808                 return;
92809             }
92810             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92811                 (resolver.isRequiredInitializedParameter(node) ||
92812                     resolver.isOptionalUninitializedParameterProperty(node));
92813             if (type && !shouldUseResolverType) {
92814                 return ts.visitNode(type, visitDeclarationSubtree);
92815             }
92816             if (!ts.getParseTreeNode(node)) {
92817                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
92818             }
92819             if (node.kind === 164 /* SetAccessor */) {
92820                 // 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
92821                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
92822                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
92823             }
92824             errorNameNode = node.name;
92825             var oldDiag;
92826             if (!suppressNewDiagnosticContexts) {
92827                 oldDiag = getSymbolAccessibilityDiagnostic;
92828                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
92829             }
92830             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92831                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92832             }
92833             if (node.kind === 156 /* Parameter */
92834                 || node.kind === 159 /* PropertyDeclaration */
92835                 || node.kind === 158 /* PropertySignature */) {
92836                 if (!node.initializer)
92837                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
92838                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92839             }
92840             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92841             function cleanup(returnValue) {
92842                 errorNameNode = undefined;
92843                 if (!suppressNewDiagnosticContexts) {
92844                     getSymbolAccessibilityDiagnostic = oldDiag;
92845                 }
92846                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
92847             }
92848         }
92849         function isDeclarationAndNotVisible(node) {
92850             node = ts.getParseTreeNode(node);
92851             switch (node.kind) {
92852                 case 244 /* FunctionDeclaration */:
92853                 case 249 /* ModuleDeclaration */:
92854                 case 246 /* InterfaceDeclaration */:
92855                 case 245 /* ClassDeclaration */:
92856                 case 247 /* TypeAliasDeclaration */:
92857                 case 248 /* EnumDeclaration */:
92858                     return !resolver.isDeclarationVisible(node);
92859                 // The following should be doing their own visibility checks based on filtering their members
92860                 case 242 /* VariableDeclaration */:
92861                     return !getBindingNameVisible(node);
92862                 case 253 /* ImportEqualsDeclaration */:
92863                 case 254 /* ImportDeclaration */:
92864                 case 260 /* ExportDeclaration */:
92865                 case 259 /* ExportAssignment */:
92866                     return false;
92867             }
92868             return false;
92869         }
92870         function getBindingNameVisible(elem) {
92871             if (ts.isOmittedExpression(elem)) {
92872                 return false;
92873             }
92874             if (ts.isBindingPattern(elem.name)) {
92875                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
92876                 return ts.some(elem.name.elements, getBindingNameVisible);
92877             }
92878             else {
92879                 return resolver.isDeclarationVisible(elem);
92880             }
92881         }
92882         function updateParamsList(node, params, modifierMask) {
92883             if (ts.hasModifier(node, 8 /* Private */)) {
92884                 return undefined; // TODO: GH#18217
92885             }
92886             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
92887             if (!newParams) {
92888                 return undefined; // TODO: GH#18217
92889             }
92890             return ts.createNodeArray(newParams, params.hasTrailingComma);
92891         }
92892         function updateAccessorParamsList(input, isPrivate) {
92893             var newParams;
92894             if (!isPrivate) {
92895                 var thisParameter = ts.getThisParameter(input);
92896                 if (thisParameter) {
92897                     newParams = [ensureParameter(thisParameter)];
92898                 }
92899             }
92900             if (ts.isSetAccessorDeclaration(input)) {
92901                 var newValueParameter = void 0;
92902                 if (!isPrivate) {
92903                     var valueParameter = ts.getSetAccessorValueParameter(input);
92904                     if (valueParameter) {
92905                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
92906                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
92907                     }
92908                 }
92909                 if (!newValueParameter) {
92910                     newValueParameter = ts.createParameter(
92911                     /*decorators*/ undefined, 
92912                     /*modifiers*/ undefined, 
92913                     /*dotDotDotToken*/ undefined, "value");
92914                 }
92915                 newParams = ts.append(newParams, newValueParameter);
92916             }
92917             return ts.createNodeArray(newParams || ts.emptyArray);
92918         }
92919         function ensureTypeParams(node, params) {
92920             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
92921         }
92922         function isEnclosingDeclaration(node) {
92923             return ts.isSourceFile(node)
92924                 || ts.isTypeAliasDeclaration(node)
92925                 || ts.isModuleDeclaration(node)
92926                 || ts.isClassDeclaration(node)
92927                 || ts.isInterfaceDeclaration(node)
92928                 || ts.isFunctionLike(node)
92929                 || ts.isIndexSignatureDeclaration(node)
92930                 || ts.isMappedTypeNode(node);
92931         }
92932         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
92933             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
92934             handleSymbolAccessibilityError(visibilityResult);
92935             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
92936         }
92937         function preserveJsDoc(updated, original) {
92938             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
92939                 updated.jsDoc = original.jsDoc;
92940             }
92941             return ts.setCommentRange(updated, ts.getCommentRange(original));
92942         }
92943         function rewriteModuleSpecifier(parent, input) {
92944             if (!input)
92945                 return undefined; // TODO: GH#18217
92946             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
92947             if (ts.isStringLiteralLike(input)) {
92948                 if (isBundledEmit) {
92949                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
92950                     if (newName) {
92951                         return ts.createLiteral(newName);
92952                     }
92953                 }
92954                 else {
92955                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
92956                     if (symbol) {
92957                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92958                     }
92959                 }
92960             }
92961             return input;
92962         }
92963         function transformImportEqualsDeclaration(decl) {
92964             if (!resolver.isDeclarationVisible(decl))
92965                 return;
92966             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
92967                 // Rewrite external module names if necessary
92968                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
92969                 return ts.updateImportEqualsDeclaration(decl, 
92970                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
92971             }
92972             else {
92973                 var oldDiag = getSymbolAccessibilityDiagnostic;
92974                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
92975                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
92976                 getSymbolAccessibilityDiagnostic = oldDiag;
92977                 return decl;
92978             }
92979         }
92980         function transformImportDeclaration(decl) {
92981             if (!decl.importClause) {
92982                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
92983                 return ts.updateImportDeclaration(decl, 
92984                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
92985             }
92986             // The `importClause` visibility corresponds to the default's visibility.
92987             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
92988             if (!decl.importClause.namedBindings) {
92989                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
92990                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
92991                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
92992             }
92993             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
92994                 // Namespace import (optionally with visible default)
92995                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
92996                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
92997             }
92998             // Named imports (optionally with visible default)
92999             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93000             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93001                 return ts.updateImportDeclaration(decl, 
93002                 /*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));
93003             }
93004             // Augmentation of export depends on import
93005             if (resolver.isImportRequiredByAugmentation(decl)) {
93006                 return ts.updateImportDeclaration(decl, 
93007                 /*decorators*/ undefined, decl.modifiers, 
93008                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93009             }
93010             // Nothing visible
93011         }
93012         function transformAndReplaceLatePaintedStatements(statements) {
93013             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93014             // error handling which must now be included in the output and themselves checked for errors.
93015             // For example:
93016             // ```
93017             // module A {
93018             //   export module Q {}
93019             //   import B = Q;
93020             //   import C = B;
93021             //   export import D = C;
93022             // }
93023             // ```
93024             // 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
93025             // 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
93026             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93027             while (ts.length(lateMarkedStatements)) {
93028                 var i = lateMarkedStatements.shift();
93029                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93030                     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));
93031                 }
93032                 var priorNeedsDeclare = needsDeclare;
93033                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93034                 var result = transformTopLevelDeclaration(i);
93035                 needsDeclare = priorNeedsDeclare;
93036                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93037             }
93038             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93039             // (and remove them from the set to examine for outter declarations)
93040             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93041             function visitLateVisibilityMarkedStatements(statement) {
93042                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93043                     var key = "" + ts.getOriginalNodeId(statement);
93044                     if (lateStatementReplacementMap.has(key)) {
93045                         var result = lateStatementReplacementMap.get(key);
93046                         lateStatementReplacementMap.delete(key);
93047                         if (result) {
93048                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93049                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93050                                 needsScopeFixMarker = true;
93051                             }
93052                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93053                                 resultHasExternalModuleIndicator = true;
93054                             }
93055                         }
93056                         return result;
93057                     }
93058                 }
93059                 return statement;
93060             }
93061         }
93062         function visitDeclarationSubtree(input) {
93063             if (shouldStripInternal(input))
93064                 return;
93065             if (ts.isDeclaration(input)) {
93066                 if (isDeclarationAndNotVisible(input))
93067                     return;
93068                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93069                     return;
93070                 }
93071             }
93072             // Elide implementation signatures from overload sets
93073             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93074                 return;
93075             // Elide semicolon class statements
93076             if (ts.isSemicolonClassElement(input))
93077                 return;
93078             var previousEnclosingDeclaration;
93079             if (isEnclosingDeclaration(input)) {
93080                 previousEnclosingDeclaration = enclosingDeclaration;
93081                 enclosingDeclaration = input;
93082             }
93083             var oldDiag = getSymbolAccessibilityDiagnostic;
93084             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93085             // We'd see a TDZ violation at runtime
93086             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93087             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93088             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93089             // Emit methods which are private as properties with no type information
93090             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93091                 if (ts.hasModifier(input, 8 /* Private */)) {
93092                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93093                         return; // Elide all but the first overload
93094                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93095                 }
93096             }
93097             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93098                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93099             }
93100             if (ts.isTypeQueryNode(input)) {
93101                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93102             }
93103             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93104                 // 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.
93105                 suppressNewDiagnosticContexts = true;
93106             }
93107             if (isProcessedComponent(input)) {
93108                 switch (input.kind) {
93109                     case 216 /* ExpressionWithTypeArguments */: {
93110                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93111                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93112                         }
93113                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93114                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93115                     }
93116                     case 169 /* TypeReference */: {
93117                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93118                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93119                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93120                     }
93121                     case 166 /* ConstructSignature */:
93122                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93123                     case 162 /* Constructor */: {
93124                         // A constructor declaration may not have a type annotation
93125                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93126                         /*type*/ undefined);
93127                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93128                         return cleanup(ctor);
93129                     }
93130                     case 161 /* MethodDeclaration */: {
93131                         if (ts.isPrivateIdentifier(input.name)) {
93132                             return cleanup(/*returnValue*/ undefined);
93133                         }
93134                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93135                         sig.name = input.name;
93136                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93137                         sig.questionToken = input.questionToken;
93138                         return cleanup(sig);
93139                     }
93140                     case 163 /* GetAccessor */: {
93141                         if (ts.isPrivateIdentifier(input.name)) {
93142                             return cleanup(/*returnValue*/ undefined);
93143                         }
93144                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93145                         return cleanup(ts.updateGetAccessor(input, 
93146                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93147                         /*body*/ undefined));
93148                     }
93149                     case 164 /* SetAccessor */: {
93150                         if (ts.isPrivateIdentifier(input.name)) {
93151                             return cleanup(/*returnValue*/ undefined);
93152                         }
93153                         return cleanup(ts.updateSetAccessor(input, 
93154                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93155                         /*body*/ undefined));
93156                     }
93157                     case 159 /* PropertyDeclaration */:
93158                         if (ts.isPrivateIdentifier(input.name)) {
93159                             return cleanup(/*returnValue*/ undefined);
93160                         }
93161                         return cleanup(ts.updateProperty(input, 
93162                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93163                     case 158 /* PropertySignature */:
93164                         if (ts.isPrivateIdentifier(input.name)) {
93165                             return cleanup(/*returnValue*/ undefined);
93166                         }
93167                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93168                     case 160 /* MethodSignature */: {
93169                         if (ts.isPrivateIdentifier(input.name)) {
93170                             return cleanup(/*returnValue*/ undefined);
93171                         }
93172                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93173                     }
93174                     case 165 /* CallSignature */: {
93175                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93176                     }
93177                     case 167 /* IndexSignature */: {
93178                         return cleanup(ts.updateIndexSignature(input, 
93179                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93180                     }
93181                     case 242 /* VariableDeclaration */: {
93182                         if (ts.isBindingPattern(input.name)) {
93183                             return recreateBindingPattern(input.name);
93184                         }
93185                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93186                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93187                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93188                     }
93189                     case 155 /* TypeParameter */: {
93190                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93191                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93192                         }
93193                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93194                     }
93195                     case 180 /* ConditionalType */: {
93196                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93197                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93198                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93199                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93200                         var oldEnclosingDecl = enclosingDeclaration;
93201                         enclosingDeclaration = input.trueType;
93202                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93203                         enclosingDeclaration = oldEnclosingDecl;
93204                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93205                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93206                     }
93207                     case 170 /* FunctionType */: {
93208                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93209                     }
93210                     case 171 /* ConstructorType */: {
93211                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93212                     }
93213                     case 188 /* ImportType */: {
93214                         if (!ts.isLiteralImportTypeNode(input))
93215                             return cleanup(input);
93216                         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));
93217                     }
93218                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93219                 }
93220             }
93221             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93222             function cleanup(returnValue) {
93223                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93224                     checkName(input);
93225                 }
93226                 if (isEnclosingDeclaration(input)) {
93227                     enclosingDeclaration = previousEnclosingDeclaration;
93228                 }
93229                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93230                     getSymbolAccessibilityDiagnostic = oldDiag;
93231                 }
93232                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93233                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93234                 }
93235                 if (returnValue === input) {
93236                     return returnValue;
93237                 }
93238                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93239             }
93240         }
93241         function isPrivateMethodTypeParameter(node) {
93242             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93243         }
93244         function visitDeclarationStatements(input) {
93245             if (!isPreservedDeclarationStatement(input)) {
93246                 // return undefined for unmatched kinds to omit them from the tree
93247                 return;
93248             }
93249             if (shouldStripInternal(input))
93250                 return;
93251             switch (input.kind) {
93252                 case 260 /* ExportDeclaration */: {
93253                     if (ts.isSourceFile(input.parent)) {
93254                         resultHasExternalModuleIndicator = true;
93255                     }
93256                     resultHasScopeMarker = true;
93257                     // Always visible if the parent node isn't dropped for being not visible
93258                     // Rewrite external module names if necessary
93259                     return ts.updateExportDeclaration(input, 
93260                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93261                 }
93262                 case 259 /* ExportAssignment */: {
93263                     // Always visible if the parent node isn't dropped for being not visible
93264                     if (ts.isSourceFile(input.parent)) {
93265                         resultHasExternalModuleIndicator = true;
93266                     }
93267                     resultHasScopeMarker = true;
93268                     if (input.expression.kind === 75 /* Identifier */) {
93269                         return input;
93270                     }
93271                     else {
93272                         var newId = ts.createOptimisticUniqueName("_default");
93273                         getSymbolAccessibilityDiagnostic = function () { return ({
93274                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93275                             errorNode: input
93276                         }); };
93277                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93278                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93279                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93280                     }
93281                 }
93282             }
93283             var result = transformTopLevelDeclaration(input);
93284             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93285             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93286             return input;
93287         }
93288         function stripExportModifiers(statement) {
93289             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93290                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93291                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93292                 return statement;
93293             }
93294             var clone = ts.getMutableClone(statement);
93295             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93296             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93297             return clone;
93298         }
93299         function transformTopLevelDeclaration(input) {
93300             if (shouldStripInternal(input))
93301                 return;
93302             switch (input.kind) {
93303                 case 253 /* ImportEqualsDeclaration */: {
93304                     return transformImportEqualsDeclaration(input);
93305                 }
93306                 case 254 /* ImportDeclaration */: {
93307                     return transformImportDeclaration(input);
93308                 }
93309             }
93310             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93311                 return;
93312             // Elide implementation signatures from overload sets
93313             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93314                 return;
93315             var previousEnclosingDeclaration;
93316             if (isEnclosingDeclaration(input)) {
93317                 previousEnclosingDeclaration = enclosingDeclaration;
93318                 enclosingDeclaration = input;
93319             }
93320             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93321             var oldDiag = getSymbolAccessibilityDiagnostic;
93322             if (canProdiceDiagnostic) {
93323                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93324             }
93325             var previousNeedsDeclare = needsDeclare;
93326             switch (input.kind) {
93327                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93328                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93329                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93330                 case 246 /* InterfaceDeclaration */: {
93331                     return cleanup(ts.updateInterfaceDeclaration(input, 
93332                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93333                 }
93334                 case 244 /* FunctionDeclaration */: {
93335                     // Generators lose their generator-ness, excepting their return type
93336                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93337                     /*decorators*/ undefined, ensureModifiers(input), 
93338                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93339                     /*body*/ undefined));
93340                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93341                         var props = resolver.getPropertiesOfContainerFunction(input);
93342                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93343                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93344                         fakespace_1.parent = enclosingDeclaration;
93345                         fakespace_1.locals = ts.createSymbolTable(props);
93346                         fakespace_1.symbol = props[0].parent;
93347                         var declarations = ts.mapDefined(props, function (p) {
93348                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93349                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93350                             }
93351                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93352                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93353                             getSymbolAccessibilityDiagnostic = oldDiag;
93354                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93355                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93356                         });
93357                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93358                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93359                             return [clean, namespaceDecl];
93360                         }
93361                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93362                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93363                         /*decorators*/ undefined, modifiers, 
93364                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93365                         /*body*/ undefined);
93366                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93367                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93368                         var exportDefaultDeclaration = ts.createExportAssignment(
93369                         /*decorators*/ undefined, 
93370                         /*modifiers*/ undefined, 
93371                         /*isExportEquals*/ false, namespaceDecl.name);
93372                         if (ts.isSourceFile(input.parent)) {
93373                             resultHasExternalModuleIndicator = true;
93374                         }
93375                         resultHasScopeMarker = true;
93376                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93377                     }
93378                     else {
93379                         return clean;
93380                     }
93381                 }
93382                 case 249 /* ModuleDeclaration */: {
93383                     needsDeclare = false;
93384                     var inner = input.body;
93385                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93386                         var oldNeedsScopeFix = needsScopeFixMarker;
93387                         var oldHasScopeFix = resultHasScopeMarker;
93388                         resultHasScopeMarker = false;
93389                         needsScopeFixMarker = false;
93390                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93391                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93392                         if (input.flags & 8388608 /* Ambient */) {
93393                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93394                         }
93395                         // With the final list of statements, there are 3 possibilities:
93396                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93397                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93398                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93399                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93400                             if (needsScopeFixMarker) {
93401                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93402                             }
93403                             else {
93404                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93405                             }
93406                         }
93407                         var body = ts.updateModuleBlock(inner, lateStatements);
93408                         needsDeclare = previousNeedsDeclare;
93409                         needsScopeFixMarker = oldNeedsScopeFix;
93410                         resultHasScopeMarker = oldHasScopeFix;
93411                         var mods = ensureModifiers(input);
93412                         return cleanup(ts.updateModuleDeclaration(input, 
93413                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93414                     }
93415                     else {
93416                         needsDeclare = previousNeedsDeclare;
93417                         var mods = ensureModifiers(input);
93418                         needsDeclare = false;
93419                         ts.visitNode(inner, visitDeclarationStatements);
93420                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93421                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93422                         var body = lateStatementReplacementMap.get(id);
93423                         lateStatementReplacementMap.delete(id);
93424                         return cleanup(ts.updateModuleDeclaration(input, 
93425                         /*decorators*/ undefined, mods, input.name, body));
93426                     }
93427                 }
93428                 case 245 /* ClassDeclaration */: {
93429                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93430                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93431                     var ctor = ts.getFirstConstructorWithBody(input);
93432                     var parameterProperties = void 0;
93433                     if (ctor) {
93434                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93435                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93436                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93437                                 return;
93438                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93439                             if (param.name.kind === 75 /* Identifier */) {
93440                                 return preserveJsDoc(ts.createProperty(
93441                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93442                             }
93443                             else {
93444                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93445                                 return walkBindingPattern(param.name);
93446                             }
93447                             function walkBindingPattern(pattern) {
93448                                 var elems;
93449                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93450                                     var elem = _a[_i];
93451                                     if (ts.isOmittedExpression(elem))
93452                                         continue;
93453                                     if (ts.isBindingPattern(elem.name)) {
93454                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93455                                     }
93456                                     elems = elems || [];
93457                                     elems.push(ts.createProperty(
93458                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93459                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93460                                     /*initializer*/ undefined));
93461                                 }
93462                                 return elems;
93463                             }
93464                         }));
93465                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93466                     }
93467                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93468                     var privateIdentifier = hasPrivateIdentifier ? [
93469                         ts.createProperty(
93470                         /*decorators*/ undefined, 
93471                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93472                         /*questionToken*/ undefined, 
93473                         /*type*/ undefined, 
93474                         /*initializer*/ undefined)
93475                     ] : undefined;
93476                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93477                     var members = ts.createNodeArray(memberNodes);
93478                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93479                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93480                         // We must add a temporary declaration for the extends clause expression
93481                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93482                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93483                         getSymbolAccessibilityDiagnostic = function () { return ({
93484                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93485                             errorNode: extendsClause_1,
93486                             typeName: input.name
93487                         }); };
93488                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93489                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93490                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93491                             if (clause.token === 90 /* ExtendsKeyword */) {
93492                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93493                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93494                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93495                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93496                                 return newClause;
93497                             }
93498                             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));
93499                         }));
93500                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93501                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93502                     }
93503                     else {
93504                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93505                         return cleanup(ts.updateClassDeclaration(input, 
93506                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93507                     }
93508                 }
93509                 case 225 /* VariableStatement */: {
93510                     return cleanup(transformVariableStatement(input));
93511                 }
93512                 case 248 /* EnumDeclaration */: {
93513                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93514                         if (shouldStripInternal(m))
93515                             return;
93516                         // Rewrite enum values to their constants, if available
93517                         var constValue = resolver.getConstantValue(m);
93518                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93519                     }))));
93520                 }
93521             }
93522             // Anything left unhandled is an error, so this should be unreachable
93523             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93524             function cleanup(node) {
93525                 if (isEnclosingDeclaration(input)) {
93526                     enclosingDeclaration = previousEnclosingDeclaration;
93527                 }
93528                 if (canProdiceDiagnostic) {
93529                     getSymbolAccessibilityDiagnostic = oldDiag;
93530                 }
93531                 if (input.kind === 249 /* ModuleDeclaration */) {
93532                     needsDeclare = previousNeedsDeclare;
93533                 }
93534                 if (node === input) {
93535                     return node;
93536                 }
93537                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93538             }
93539         }
93540         function transformVariableStatement(input) {
93541             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93542                 return;
93543             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93544             if (!ts.length(nodes))
93545                 return;
93546             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93547         }
93548         function recreateBindingPattern(d) {
93549             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93550         }
93551         function recreateBindingElement(e) {
93552             if (e.kind === 215 /* OmittedExpression */) {
93553                 return;
93554             }
93555             if (e.name) {
93556                 if (!getBindingNameVisible(e))
93557                     return;
93558                 if (ts.isBindingPattern(e.name)) {
93559                     return recreateBindingPattern(e.name);
93560                 }
93561                 else {
93562                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93563                 }
93564             }
93565         }
93566         function checkName(node) {
93567             var oldDiag;
93568             if (!suppressNewDiagnosticContexts) {
93569                 oldDiag = getSymbolAccessibilityDiagnostic;
93570                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93571             }
93572             errorNameNode = node.name;
93573             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93574             var decl = node;
93575             var entityName = decl.name.expression;
93576             checkEntityNameVisibility(entityName, enclosingDeclaration);
93577             if (!suppressNewDiagnosticContexts) {
93578                 getSymbolAccessibilityDiagnostic = oldDiag;
93579             }
93580             errorNameNode = undefined;
93581         }
93582         function shouldStripInternal(node) {
93583             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93584         }
93585         function isScopeMarker(node) {
93586             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93587         }
93588         function hasScopeMarker(statements) {
93589             return ts.some(statements, isScopeMarker);
93590         }
93591         function ensureModifiers(node) {
93592             var currentFlags = ts.getModifierFlags(node);
93593             var newFlags = ensureModifierFlags(node);
93594             if (currentFlags === newFlags) {
93595                 return node.modifiers;
93596             }
93597             return ts.createModifiersFromModifierFlags(newFlags);
93598         }
93599         function ensureModifierFlags(node) {
93600             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93601             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93602             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93603             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93604                 mask ^= 2 /* Ambient */;
93605                 additions = 0 /* None */;
93606             }
93607             return maskModifierFlags(node, mask, additions);
93608         }
93609         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93610             var accessorType = getTypeAnnotationFromAccessor(node);
93611             if (!accessorType && node !== accessors.firstAccessor) {
93612                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93613                 // 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
93614                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93615             }
93616             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93617                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93618                 // 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
93619                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93620             }
93621             return accessorType;
93622         }
93623         function transformHeritageClauses(nodes) {
93624             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93625                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93626             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93627         }
93628     }
93629     ts.transformDeclarations = transformDeclarations;
93630     function isAlwaysType(node) {
93631         if (node.kind === 246 /* InterfaceDeclaration */) {
93632             return true;
93633         }
93634         return false;
93635     }
93636     // Elide "public" modifier, as it is the default
93637     function maskModifiers(node, modifierMask, modifierAdditions) {
93638         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93639     }
93640     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93641         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93642         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93643         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93644         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93645             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93646             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93647             flags ^= 1 /* Export */;
93648         }
93649         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93650             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93651         }
93652         return flags;
93653     }
93654     function getTypeAnnotationFromAccessor(accessor) {
93655         if (accessor) {
93656             return accessor.kind === 163 /* GetAccessor */
93657                 ? accessor.type // Getter - return type
93658                 : accessor.parameters.length > 0
93659                     ? accessor.parameters[0].type // Setter parameter type
93660                     : undefined;
93661         }
93662     }
93663     function canHaveLiteralInitializer(node) {
93664         switch (node.kind) {
93665             case 159 /* PropertyDeclaration */:
93666             case 158 /* PropertySignature */:
93667                 return !ts.hasModifier(node, 8 /* Private */);
93668             case 156 /* Parameter */:
93669             case 242 /* VariableDeclaration */:
93670                 return true;
93671         }
93672         return false;
93673     }
93674     function isPreservedDeclarationStatement(node) {
93675         switch (node.kind) {
93676             case 244 /* FunctionDeclaration */:
93677             case 249 /* ModuleDeclaration */:
93678             case 253 /* ImportEqualsDeclaration */:
93679             case 246 /* InterfaceDeclaration */:
93680             case 245 /* ClassDeclaration */:
93681             case 247 /* TypeAliasDeclaration */:
93682             case 248 /* EnumDeclaration */:
93683             case 225 /* VariableStatement */:
93684             case 254 /* ImportDeclaration */:
93685             case 260 /* ExportDeclaration */:
93686             case 259 /* ExportAssignment */:
93687                 return true;
93688         }
93689         return false;
93690     }
93691     function isProcessedComponent(node) {
93692         switch (node.kind) {
93693             case 166 /* ConstructSignature */:
93694             case 162 /* Constructor */:
93695             case 161 /* MethodDeclaration */:
93696             case 163 /* GetAccessor */:
93697             case 164 /* SetAccessor */:
93698             case 159 /* PropertyDeclaration */:
93699             case 158 /* PropertySignature */:
93700             case 160 /* MethodSignature */:
93701             case 165 /* CallSignature */:
93702             case 167 /* IndexSignature */:
93703             case 242 /* VariableDeclaration */:
93704             case 155 /* TypeParameter */:
93705             case 216 /* ExpressionWithTypeArguments */:
93706             case 169 /* TypeReference */:
93707             case 180 /* ConditionalType */:
93708             case 170 /* FunctionType */:
93709             case 171 /* ConstructorType */:
93710             case 188 /* ImportType */:
93711                 return true;
93712         }
93713         return false;
93714     }
93715 })(ts || (ts = {}));
93716 /* @internal */
93717 var ts;
93718 (function (ts) {
93719     function getModuleTransformer(moduleKind) {
93720         switch (moduleKind) {
93721             case ts.ModuleKind.ESNext:
93722             case ts.ModuleKind.ES2020:
93723             case ts.ModuleKind.ES2015:
93724                 return ts.transformECMAScriptModule;
93725             case ts.ModuleKind.System:
93726                 return ts.transformSystemModule;
93727             default:
93728                 return ts.transformModule;
93729         }
93730     }
93731     var TransformationState;
93732     (function (TransformationState) {
93733         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93734         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93735         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93736         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93737     })(TransformationState || (TransformationState = {}));
93738     var SyntaxKindFeatureFlags;
93739     (function (SyntaxKindFeatureFlags) {
93740         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93741         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93742     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93743     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93744     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93745         return {
93746             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93747             declarationTransformers: getDeclarationTransformers(customTransformers),
93748         };
93749     }
93750     ts.getTransformers = getTransformers;
93751     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93752         if (emitOnlyDtsFiles)
93753             return ts.emptyArray;
93754         var jsx = compilerOptions.jsx;
93755         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93756         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93757         var transformers = [];
93758         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93759         transformers.push(ts.transformTypeScript);
93760         transformers.push(ts.transformClassFields);
93761         if (jsx === 2 /* React */) {
93762             transformers.push(ts.transformJsx);
93763         }
93764         if (languageVersion < 99 /* ESNext */) {
93765             transformers.push(ts.transformESNext);
93766         }
93767         if (languageVersion < 7 /* ES2020 */) {
93768             transformers.push(ts.transformES2020);
93769         }
93770         if (languageVersion < 6 /* ES2019 */) {
93771             transformers.push(ts.transformES2019);
93772         }
93773         if (languageVersion < 5 /* ES2018 */) {
93774             transformers.push(ts.transformES2018);
93775         }
93776         if (languageVersion < 4 /* ES2017 */) {
93777             transformers.push(ts.transformES2017);
93778         }
93779         if (languageVersion < 3 /* ES2016 */) {
93780             transformers.push(ts.transformES2016);
93781         }
93782         if (languageVersion < 2 /* ES2015 */) {
93783             transformers.push(ts.transformES2015);
93784             transformers.push(ts.transformGenerators);
93785         }
93786         transformers.push(getModuleTransformer(moduleKind));
93787         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93788         // for ES3.
93789         if (languageVersion < 1 /* ES5 */) {
93790             transformers.push(ts.transformES5);
93791         }
93792         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93793         return transformers;
93794     }
93795     function getDeclarationTransformers(customTransformers) {
93796         var transformers = [];
93797         transformers.push(ts.transformDeclarations);
93798         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93799         return transformers;
93800     }
93801     /**
93802      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93803      */
93804     function wrapCustomTransformer(transformer) {
93805         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93806     }
93807     /**
93808      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93809      */
93810     function wrapCustomTransformerFactory(transformer, handleDefault) {
93811         return function (context) {
93812             var customTransformer = transformer(context);
93813             return typeof customTransformer === "function"
93814                 ? handleDefault(customTransformer)
93815                 : wrapCustomTransformer(customTransformer);
93816         };
93817     }
93818     function wrapScriptTransformerFactory(transformer) {
93819         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
93820     }
93821     function wrapDeclarationTransformerFactory(transformer) {
93822         return wrapCustomTransformerFactory(transformer, ts.identity);
93823     }
93824     function noEmitSubstitution(_hint, node) {
93825         return node;
93826     }
93827     ts.noEmitSubstitution = noEmitSubstitution;
93828     function noEmitNotification(hint, node, callback) {
93829         callback(hint, node);
93830     }
93831     ts.noEmitNotification = noEmitNotification;
93832     /**
93833      * Transforms an array of SourceFiles by passing them through each transformer.
93834      *
93835      * @param resolver The emit resolver provided by the checker.
93836      * @param host The emit host object used to interact with the file system.
93837      * @param options Compiler options to surface in the `TransformationContext`.
93838      * @param nodes An array of nodes to transform.
93839      * @param transforms An array of `TransformerFactory` callbacks.
93840      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
93841      */
93842     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
93843         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
93844         var lexicalEnvironmentVariableDeclarations;
93845         var lexicalEnvironmentFunctionDeclarations;
93846         var lexicalEnvironmentStatements;
93847         var lexicalEnvironmentFlags = 0 /* None */;
93848         var lexicalEnvironmentVariableDeclarationsStack = [];
93849         var lexicalEnvironmentFunctionDeclarationsStack = [];
93850         var lexicalEnvironmentStatementsStack = [];
93851         var lexicalEnvironmentFlagsStack = [];
93852         var lexicalEnvironmentStackOffset = 0;
93853         var lexicalEnvironmentSuspended = false;
93854         var emitHelpers;
93855         var onSubstituteNode = noEmitSubstitution;
93856         var onEmitNode = noEmitNotification;
93857         var state = 0 /* Uninitialized */;
93858         var diagnostics = [];
93859         // The transformation context is provided to each transformer as part of transformer
93860         // initialization.
93861         var context = {
93862             getCompilerOptions: function () { return options; },
93863             getEmitResolver: function () { return resolver; },
93864             getEmitHost: function () { return host; },
93865             startLexicalEnvironment: startLexicalEnvironment,
93866             suspendLexicalEnvironment: suspendLexicalEnvironment,
93867             resumeLexicalEnvironment: resumeLexicalEnvironment,
93868             endLexicalEnvironment: endLexicalEnvironment,
93869             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
93870             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
93871             hoistVariableDeclaration: hoistVariableDeclaration,
93872             hoistFunctionDeclaration: hoistFunctionDeclaration,
93873             addInitializationStatement: addInitializationStatement,
93874             requestEmitHelper: requestEmitHelper,
93875             readEmitHelpers: readEmitHelpers,
93876             enableSubstitution: enableSubstitution,
93877             enableEmitNotification: enableEmitNotification,
93878             isSubstitutionEnabled: isSubstitutionEnabled,
93879             isEmitNotificationEnabled: isEmitNotificationEnabled,
93880             get onSubstituteNode() { return onSubstituteNode; },
93881             set onSubstituteNode(value) {
93882                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93883                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93884                 onSubstituteNode = value;
93885             },
93886             get onEmitNode() { return onEmitNode; },
93887             set onEmitNode(value) {
93888                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93889                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93890                 onEmitNode = value;
93891             },
93892             addDiagnostic: function (diag) {
93893                 diagnostics.push(diag);
93894             }
93895         };
93896         // Ensure the parse tree is clean before applying transformations
93897         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
93898             var node = nodes_4[_i];
93899             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
93900         }
93901         ts.performance.mark("beforeTransform");
93902         // Chain together and initialize each transformer.
93903         var transformersWithContext = transformers.map(function (t) { return t(context); });
93904         var transformation = function (node) {
93905             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
93906                 var transform = transformersWithContext_1[_i];
93907                 node = transform(node);
93908             }
93909             return node;
93910         };
93911         // prevent modification of transformation hooks.
93912         state = 1 /* Initialized */;
93913         // Transform each node.
93914         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
93915         // prevent modification of the lexical environment.
93916         state = 2 /* Completed */;
93917         ts.performance.mark("afterTransform");
93918         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
93919         return {
93920             transformed: transformed,
93921             substituteNode: substituteNode,
93922             emitNodeWithNotification: emitNodeWithNotification,
93923             isEmitNotificationEnabled: isEmitNotificationEnabled,
93924             dispose: dispose,
93925             diagnostics: diagnostics
93926         };
93927         function transformRoot(node) {
93928             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
93929         }
93930         /**
93931          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
93932          */
93933         function enableSubstitution(kind) {
93934             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93935             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
93936         }
93937         /**
93938          * Determines whether expression substitutions are enabled for the provided node.
93939          */
93940         function isSubstitutionEnabled(node) {
93941             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
93942                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
93943         }
93944         /**
93945          * Emits a node with possible substitution.
93946          *
93947          * @param hint A hint as to the intended usage of the node.
93948          * @param node The node to emit.
93949          * @param emitCallback The callback used to emit the node or its substitute.
93950          */
93951         function substituteNode(hint, node) {
93952             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
93953             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
93954         }
93955         /**
93956          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
93957          */
93958         function enableEmitNotification(kind) {
93959             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93960             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
93961         }
93962         /**
93963          * Determines whether before/after emit notifications should be raised in the pretty
93964          * printer when it emits a node.
93965          */
93966         function isEmitNotificationEnabled(node) {
93967             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
93968                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
93969         }
93970         /**
93971          * Emits a node with possible emit notification.
93972          *
93973          * @param hint A hint as to the intended usage of the node.
93974          * @param node The node to emit.
93975          * @param emitCallback The callback used to emit the node.
93976          */
93977         function emitNodeWithNotification(hint, node, emitCallback) {
93978             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
93979             if (node) {
93980                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
93981                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
93982                 if (isEmitNotificationEnabled(node)) {
93983                     onEmitNode(hint, node, emitCallback);
93984                 }
93985                 else {
93986                     emitCallback(hint, node);
93987                 }
93988             }
93989         }
93990         /**
93991          * Records a hoisted variable declaration for the provided name within a lexical environment.
93992          */
93993         function hoistVariableDeclaration(name) {
93994             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
93995             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
93996             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
93997             if (!lexicalEnvironmentVariableDeclarations) {
93998                 lexicalEnvironmentVariableDeclarations = [decl];
93999             }
94000             else {
94001                 lexicalEnvironmentVariableDeclarations.push(decl);
94002             }
94003             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94004                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94005             }
94006         }
94007         /**
94008          * Records a hoisted function declaration within a lexical environment.
94009          */
94010         function hoistFunctionDeclaration(func) {
94011             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94012             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94013             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
94014             if (!lexicalEnvironmentFunctionDeclarations) {
94015                 lexicalEnvironmentFunctionDeclarations = [func];
94016             }
94017             else {
94018                 lexicalEnvironmentFunctionDeclarations.push(func);
94019             }
94020         }
94021         /**
94022          * Adds an initialization statement to the top of the lexical environment.
94023          */
94024         function addInitializationStatement(node) {
94025             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94026             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94027             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94028             if (!lexicalEnvironmentStatements) {
94029                 lexicalEnvironmentStatements = [node];
94030             }
94031             else {
94032                 lexicalEnvironmentStatements.push(node);
94033             }
94034         }
94035         /**
94036          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94037          * are pushed onto a stack, and the related storage variables are reset.
94038          */
94039         function startLexicalEnvironment() {
94040             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94041             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94042             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94043             // Save the current lexical environment. Rather than resizing the array we adjust the
94044             // stack size variable. This allows us to reuse existing array slots we've
94045             // already allocated between transformations to avoid allocation and GC overhead during
94046             // transformation.
94047             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94048             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94049             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94050             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94051             lexicalEnvironmentStackOffset++;
94052             lexicalEnvironmentVariableDeclarations = undefined;
94053             lexicalEnvironmentFunctionDeclarations = undefined;
94054             lexicalEnvironmentStatements = undefined;
94055             lexicalEnvironmentFlags = 0 /* None */;
94056         }
94057         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94058         function suspendLexicalEnvironment() {
94059             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94060             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94061             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94062             lexicalEnvironmentSuspended = true;
94063         }
94064         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94065         function resumeLexicalEnvironment() {
94066             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94067             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94068             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94069             lexicalEnvironmentSuspended = false;
94070         }
94071         /**
94072          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94073          * any hoisted declarations added in this environment are returned.
94074          */
94075         function endLexicalEnvironment() {
94076             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94077             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94078             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94079             var statements;
94080             if (lexicalEnvironmentVariableDeclarations ||
94081                 lexicalEnvironmentFunctionDeclarations ||
94082                 lexicalEnvironmentStatements) {
94083                 if (lexicalEnvironmentFunctionDeclarations) {
94084                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94085                 }
94086                 if (lexicalEnvironmentVariableDeclarations) {
94087                     var statement = ts.createVariableStatement(
94088                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94089                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94090                     if (!statements) {
94091                         statements = [statement];
94092                     }
94093                     else {
94094                         statements.push(statement);
94095                     }
94096                 }
94097                 if (lexicalEnvironmentStatements) {
94098                     if (!statements) {
94099                         statements = __spreadArrays(lexicalEnvironmentStatements);
94100                     }
94101                     else {
94102                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94103                     }
94104                 }
94105             }
94106             // Restore the previous lexical environment.
94107             lexicalEnvironmentStackOffset--;
94108             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94109             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94110             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94111             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94112             if (lexicalEnvironmentStackOffset === 0) {
94113                 lexicalEnvironmentVariableDeclarationsStack = [];
94114                 lexicalEnvironmentFunctionDeclarationsStack = [];
94115                 lexicalEnvironmentStatementsStack = [];
94116                 lexicalEnvironmentFlagsStack = [];
94117             }
94118             return statements;
94119         }
94120         function setLexicalEnvironmentFlags(flags, value) {
94121             lexicalEnvironmentFlags = value ?
94122                 lexicalEnvironmentFlags | flags :
94123                 lexicalEnvironmentFlags & ~flags;
94124         }
94125         function getLexicalEnvironmentFlags() {
94126             return lexicalEnvironmentFlags;
94127         }
94128         function requestEmitHelper(helper) {
94129             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94130             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94131             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94132             if (helper.dependencies) {
94133                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94134                     var h = _a[_i];
94135                     requestEmitHelper(h);
94136                 }
94137             }
94138             emitHelpers = ts.append(emitHelpers, helper);
94139         }
94140         function readEmitHelpers() {
94141             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94142             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94143             var helpers = emitHelpers;
94144             emitHelpers = undefined;
94145             return helpers;
94146         }
94147         function dispose() {
94148             if (state < 3 /* Disposed */) {
94149                 // Clean up emit nodes on parse tree
94150                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94151                     var node = nodes_5[_i];
94152                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94153                 }
94154                 // Release references to external entries for GC purposes.
94155                 lexicalEnvironmentVariableDeclarations = undefined;
94156                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94157                 lexicalEnvironmentFunctionDeclarations = undefined;
94158                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94159                 onSubstituteNode = undefined;
94160                 onEmitNode = undefined;
94161                 emitHelpers = undefined;
94162                 // Prevent further use of the transformation result.
94163                 state = 3 /* Disposed */;
94164             }
94165         }
94166     }
94167     ts.transformNodes = transformNodes;
94168 })(ts || (ts = {}));
94169 var ts;
94170 (function (ts) {
94171     var brackets = createBracketsMap();
94172     var syntheticParent = { pos: -1, end: -1 };
94173     /*@internal*/
94174     function isBuildInfoFile(file) {
94175         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94176     }
94177     ts.isBuildInfoFile = isBuildInfoFile;
94178     /*@internal*/
94179     /**
94180      * Iterates over the source files that are expected to have an emit output.
94181      *
94182      * @param host An EmitHost.
94183      * @param action The action to execute.
94184      * @param sourceFilesOrTargetSourceFile
94185      *   If an array, the full list of source files to emit.
94186      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94187      */
94188     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94189         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94190         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94191         var options = host.getCompilerOptions();
94192         if (options.outFile || options.out) {
94193             var prepends = host.getPrependNodes();
94194             if (sourceFiles.length || prepends.length) {
94195                 var bundle = ts.createBundle(sourceFiles, prepends);
94196                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94197                 if (result) {
94198                     return result;
94199                 }
94200             }
94201         }
94202         else {
94203             if (!onlyBuildInfo) {
94204                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94205                     var sourceFile = sourceFiles_1[_a];
94206                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94207                     if (result) {
94208                         return result;
94209                     }
94210                 }
94211             }
94212             if (includeBuildInfo) {
94213                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94214                 if (buildInfoPath)
94215                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94216             }
94217         }
94218     }
94219     ts.forEachEmittedFile = forEachEmittedFile;
94220     function getTsBuildInfoEmitOutputFilePath(options) {
94221         var configFile = options.configFilePath;
94222         if (!ts.isIncrementalCompilation(options))
94223             return undefined;
94224         if (options.tsBuildInfoFile)
94225             return options.tsBuildInfoFile;
94226         var outPath = options.outFile || options.out;
94227         var buildInfoExtensionLess;
94228         if (outPath) {
94229             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94230         }
94231         else {
94232             if (!configFile)
94233                 return undefined;
94234             var configFileExtensionLess = ts.removeFileExtension(configFile);
94235             buildInfoExtensionLess = options.outDir ?
94236                 options.rootDir ?
94237                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94238                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94239                 configFileExtensionLess;
94240         }
94241         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94242     }
94243     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94244     /*@internal*/
94245     function getOutputPathsForBundle(options, forceDtsPaths) {
94246         var outPath = options.outFile || options.out;
94247         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94248         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94249         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94250         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94251         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94252         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94253     }
94254     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94255     /*@internal*/
94256     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94257         var options = host.getCompilerOptions();
94258         if (sourceFile.kind === 291 /* Bundle */) {
94259             return getOutputPathsForBundle(options, forceDtsPaths);
94260         }
94261         else {
94262             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94263             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94264             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94265             var isJsonEmittedToSameLocation = isJsonFile &&
94266                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94267             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94268             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94269             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94270             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94271             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94272         }
94273     }
94274     ts.getOutputPathsFor = getOutputPathsFor;
94275     function getSourceMapFilePath(jsFilePath, options) {
94276         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94277     }
94278     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94279     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94280     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94281     /* @internal */
94282     function getOutputExtension(sourceFile, options) {
94283         if (ts.isJsonSourceFile(sourceFile)) {
94284             return ".json" /* Json */;
94285         }
94286         if (options.jsx === 1 /* Preserve */) {
94287             if (ts.isSourceFileJS(sourceFile)) {
94288                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94289                     return ".jsx" /* Jsx */;
94290                 }
94291             }
94292             else if (sourceFile.languageVariant === 1 /* JSX */) {
94293                 // TypeScript source file preserving JSX syntax
94294                 return ".jsx" /* Jsx */;
94295             }
94296         }
94297         return ".js" /* Js */;
94298     }
94299     ts.getOutputExtension = getOutputExtension;
94300     function rootDirOfOptions(configFile) {
94301         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94302     }
94303     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94304         return outputDir ?
94305             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94306             inputFileName;
94307     }
94308     /* @internal */
94309     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94310         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94311         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94312     }
94313     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94314     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94315         if (configFile.options.emitDeclarationOnly)
94316             return undefined;
94317         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94318         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94319             ".json" /* Json */ :
94320             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94321                 ".jsx" /* Jsx */ :
94322                 ".js" /* Js */);
94323         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94324             outputFileName :
94325             undefined;
94326     }
94327     function createAddOutput() {
94328         var outputs;
94329         return { addOutput: addOutput, getOutputs: getOutputs };
94330         function addOutput(path) {
94331             if (path) {
94332                 (outputs || (outputs = [])).push(path);
94333             }
94334         }
94335         function getOutputs() {
94336             return outputs || ts.emptyArray;
94337         }
94338     }
94339     function getSingleOutputFileNames(configFile, addOutput) {
94340         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94341         addOutput(jsFilePath);
94342         addOutput(sourceMapFilePath);
94343         addOutput(declarationFilePath);
94344         addOutput(declarationMapPath);
94345         addOutput(buildInfoPath);
94346     }
94347     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94348         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94349             return;
94350         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94351         addOutput(js);
94352         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94353             return;
94354         if (js && configFile.options.sourceMap) {
94355             addOutput(js + ".map");
94356         }
94357         if (ts.getEmitDeclarations(configFile.options)) {
94358             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94359             addOutput(dts);
94360             if (configFile.options.declarationMap) {
94361                 addOutput(dts + ".map");
94362             }
94363         }
94364     }
94365     /*@internal*/
94366     function getAllProjectOutputs(configFile, ignoreCase) {
94367         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94368         if (configFile.options.outFile || configFile.options.out) {
94369             getSingleOutputFileNames(configFile, addOutput);
94370         }
94371         else {
94372             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94373                 var inputFileName = _c[_b];
94374                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94375             }
94376             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94377         }
94378         return getOutputs();
94379     }
94380     ts.getAllProjectOutputs = getAllProjectOutputs;
94381     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94382         inputFileName = ts.normalizePath(inputFileName);
94383         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94384         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94385         if (commandLine.options.outFile || commandLine.options.out) {
94386             getSingleOutputFileNames(commandLine, addOutput);
94387         }
94388         else {
94389             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94390         }
94391         return getOutputs();
94392     }
94393     ts.getOutputFileNames = getOutputFileNames;
94394     /*@internal*/
94395     function getFirstProjectOutput(configFile, ignoreCase) {
94396         if (configFile.options.outFile || configFile.options.out) {
94397             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94398             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94399         }
94400         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94401             var inputFileName = _b[_a];
94402             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94403                 continue;
94404             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94405             if (jsFilePath)
94406                 return jsFilePath;
94407             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94408                 continue;
94409             if (ts.getEmitDeclarations(configFile.options)) {
94410                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94411             }
94412         }
94413         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94414         if (buildInfoPath)
94415             return buildInfoPath;
94416         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94417     }
94418     ts.getFirstProjectOutput = getFirstProjectOutput;
94419     /*@internal*/
94420     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94421     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94422         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94423         var compilerOptions = host.getCompilerOptions();
94424         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94425         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94426         var emitterDiagnostics = ts.createDiagnosticCollection();
94427         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94428         var writer = ts.createTextWriter(newLine);
94429         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94430         var bundleBuildInfo;
94431         var emitSkipped = false;
94432         var exportedModulesFromDeclarationEmit;
94433         // Emit each output file
94434         enter();
94435         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94436         exit();
94437         return {
94438             emitSkipped: emitSkipped,
94439             diagnostics: emitterDiagnostics.getDiagnostics(),
94440             emittedFiles: emittedFilesList,
94441             sourceMaps: sourceMapDataList,
94442             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94443         };
94444         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94445             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94446             var buildInfoDirectory;
94447             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94448                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94449                 bundleBuildInfo = {
94450                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94451                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94452                 };
94453             }
94454             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94455             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94456             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94457             if (!emitSkipped && emittedFilesList) {
94458                 if (!emitOnlyDtsFiles) {
94459                     if (jsFilePath) {
94460                         emittedFilesList.push(jsFilePath);
94461                     }
94462                     if (sourceMapFilePath) {
94463                         emittedFilesList.push(sourceMapFilePath);
94464                     }
94465                     if (buildInfoPath) {
94466                         emittedFilesList.push(buildInfoPath);
94467                     }
94468                 }
94469                 if (declarationFilePath) {
94470                     emittedFilesList.push(declarationFilePath);
94471                 }
94472                 if (declarationMapPath) {
94473                     emittedFilesList.push(declarationMapPath);
94474                 }
94475             }
94476             function relativeToBuildInfo(path) {
94477                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94478             }
94479         }
94480         function emitBuildInfo(bundle, buildInfoPath) {
94481             // Write build information if applicable
94482             if (!buildInfoPath || targetSourceFile || emitSkipped)
94483                 return;
94484             var program = host.getProgramBuildInfo();
94485             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94486                 emitSkipped = true;
94487                 return;
94488             }
94489             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94490             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94491         }
94492         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94493             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94494                 return;
94495             }
94496             // Make sure not to write js file and source map file if any of them cannot be written
94497             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94498                 emitSkipped = true;
94499                 return;
94500             }
94501             // Transform the source files
94502             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94503             var printerOptions = {
94504                 removeComments: compilerOptions.removeComments,
94505                 newLine: compilerOptions.newLine,
94506                 noEmitHelpers: compilerOptions.noEmitHelpers,
94507                 module: compilerOptions.module,
94508                 target: compilerOptions.target,
94509                 sourceMap: compilerOptions.sourceMap,
94510                 inlineSourceMap: compilerOptions.inlineSourceMap,
94511                 inlineSources: compilerOptions.inlineSources,
94512                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94513                 writeBundleFileInfo: !!bundleBuildInfo,
94514                 relativeToBuildInfo: relativeToBuildInfo
94515             };
94516             // Create a printer to print the nodes
94517             var printer = createPrinter(printerOptions, {
94518                 // resolver hooks
94519                 hasGlobalName: resolver.hasGlobalName,
94520                 // transform hooks
94521                 onEmitNode: transform.emitNodeWithNotification,
94522                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94523                 substituteNode: transform.substituteNode,
94524             });
94525             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94526             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94527             // Clean up emit nodes on parse tree
94528             transform.dispose();
94529             if (bundleBuildInfo)
94530                 bundleBuildInfo.js = printer.bundleFileInfo;
94531         }
94532         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94533             if (!sourceFileOrBundle)
94534                 return;
94535             if (!declarationFilePath) {
94536                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94537                     emitSkipped = true;
94538                 return;
94539             }
94540             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94541             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94542             // Setup and perform the transformation to retrieve declarations from the input files
94543             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94544             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94545                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94546                 // Do that here when emitting only dts files
94547                 filesForEmit.forEach(collectLinkedAliases);
94548             }
94549             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94550             if (ts.length(declarationTransform.diagnostics)) {
94551                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94552                     var diagnostic = _b[_a];
94553                     emitterDiagnostics.add(diagnostic);
94554                 }
94555             }
94556             var printerOptions = {
94557                 removeComments: compilerOptions.removeComments,
94558                 newLine: compilerOptions.newLine,
94559                 noEmitHelpers: true,
94560                 module: compilerOptions.module,
94561                 target: compilerOptions.target,
94562                 sourceMap: compilerOptions.sourceMap,
94563                 inlineSourceMap: compilerOptions.inlineSourceMap,
94564                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94565                 onlyPrintJsDocStyle: true,
94566                 writeBundleFileInfo: !!bundleBuildInfo,
94567                 recordInternalSection: !!bundleBuildInfo,
94568                 relativeToBuildInfo: relativeToBuildInfo
94569             };
94570             var declarationPrinter = createPrinter(printerOptions, {
94571                 // resolver hooks
94572                 hasGlobalName: resolver.hasGlobalName,
94573                 // transform hooks
94574                 onEmitNode: declarationTransform.emitNodeWithNotification,
94575                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94576                 substituteNode: declarationTransform.substituteNode,
94577             });
94578             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94579             emitSkipped = emitSkipped || declBlocked;
94580             if (!declBlocked || forceDtsEmit) {
94581                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94582                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94583                     sourceMap: compilerOptions.declarationMap,
94584                     sourceRoot: compilerOptions.sourceRoot,
94585                     mapRoot: compilerOptions.mapRoot,
94586                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94587                 });
94588                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94589                     var sourceFile = declarationTransform.transformed[0];
94590                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94591                 }
94592             }
94593             declarationTransform.dispose();
94594             if (bundleBuildInfo)
94595                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94596         }
94597         function collectLinkedAliases(node) {
94598             if (ts.isExportAssignment(node)) {
94599                 if (node.expression.kind === 75 /* Identifier */) {
94600                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94601                 }
94602                 return;
94603             }
94604             else if (ts.isExportSpecifier(node)) {
94605                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94606                 return;
94607             }
94608             ts.forEachChild(node, collectLinkedAliases);
94609         }
94610         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94611             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94612             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94613             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94614             var sourceMapGenerator;
94615             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94616                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94617             }
94618             if (bundle) {
94619                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94620             }
94621             else {
94622                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94623             }
94624             if (sourceMapGenerator) {
94625                 if (sourceMapDataList) {
94626                     sourceMapDataList.push({
94627                         inputSourceFileNames: sourceMapGenerator.getSources(),
94628                         sourceMap: sourceMapGenerator.toJSON()
94629                     });
94630                 }
94631                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94632                 if (sourceMappingURL) {
94633                     if (!writer.isAtStartOfLine())
94634                         writer.rawWrite(newLine);
94635                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94636                 }
94637                 // Write the source map
94638                 if (sourceMapFilePath) {
94639                     var sourceMap = sourceMapGenerator.toString();
94640                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94641                 }
94642             }
94643             else {
94644                 writer.writeLine();
94645             }
94646             // Write the output file
94647             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94648             // Reset state
94649             writer.clear();
94650         }
94651         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94652             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94653                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94654         }
94655         function getSourceRoot(mapOptions) {
94656             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94657             // relative paths of the sources list in the sourcemap
94658             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94659             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94660         }
94661         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94662             if (mapOptions.sourceRoot)
94663                 return host.getCommonSourceDirectory();
94664             if (mapOptions.mapRoot) {
94665                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94666                 if (sourceFile) {
94667                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94668                     // 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
94669                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94670                 }
94671                 if (ts.getRootLength(sourceMapDir) === 0) {
94672                     // The relative paths are relative to the common directory
94673                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94674                 }
94675                 return sourceMapDir;
94676             }
94677             return ts.getDirectoryPath(ts.normalizePath(filePath));
94678         }
94679         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94680             if (mapOptions.inlineSourceMap) {
94681                 // Encode the sourceMap into the sourceMap url
94682                 var sourceMapText = sourceMapGenerator.toString();
94683                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94684                 return "data:application/json;base64," + base64SourceMapText;
94685             }
94686             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94687             if (mapOptions.mapRoot) {
94688                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94689                 if (sourceFile) {
94690                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94691                     // 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
94692                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94693                 }
94694                 if (ts.getRootLength(sourceMapDir) === 0) {
94695                     // The relative paths are relative to the common directory
94696                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94697                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94698                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94699                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94700                     /*isAbsolutePathAnUrl*/ true);
94701                 }
94702                 else {
94703                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94704                 }
94705             }
94706             return sourceMapFile;
94707         }
94708     }
94709     ts.emitFiles = emitFiles;
94710     /*@internal*/
94711     function getBuildInfoText(buildInfo) {
94712         return JSON.stringify(buildInfo, undefined, 2);
94713     }
94714     ts.getBuildInfoText = getBuildInfoText;
94715     /*@internal*/
94716     function getBuildInfo(buildInfoText) {
94717         return JSON.parse(buildInfoText);
94718     }
94719     ts.getBuildInfo = getBuildInfo;
94720     /*@internal*/
94721     ts.notImplementedResolver = {
94722         hasGlobalName: ts.notImplemented,
94723         getReferencedExportContainer: ts.notImplemented,
94724         getReferencedImportDeclaration: ts.notImplemented,
94725         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94726         isDeclarationWithCollidingName: ts.notImplemented,
94727         isValueAliasDeclaration: ts.notImplemented,
94728         isReferencedAliasDeclaration: ts.notImplemented,
94729         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94730         getNodeCheckFlags: ts.notImplemented,
94731         isDeclarationVisible: ts.notImplemented,
94732         isLateBound: function (_node) { return false; },
94733         collectLinkedAliases: ts.notImplemented,
94734         isImplementationOfOverload: ts.notImplemented,
94735         isRequiredInitializedParameter: ts.notImplemented,
94736         isOptionalUninitializedParameterProperty: ts.notImplemented,
94737         isExpandoFunctionDeclaration: ts.notImplemented,
94738         getPropertiesOfContainerFunction: ts.notImplemented,
94739         createTypeOfDeclaration: ts.notImplemented,
94740         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94741         createTypeOfExpression: ts.notImplemented,
94742         createLiteralConstValue: ts.notImplemented,
94743         isSymbolAccessible: ts.notImplemented,
94744         isEntityNameVisible: ts.notImplemented,
94745         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94746         getConstantValue: ts.notImplemented,
94747         getReferencedValueDeclaration: ts.notImplemented,
94748         getTypeReferenceSerializationKind: ts.notImplemented,
94749         isOptionalParameter: ts.notImplemented,
94750         moduleExportsSomeValue: ts.notImplemented,
94751         isArgumentsLocalBinding: ts.notImplemented,
94752         getExternalModuleFileFromDeclaration: ts.notImplemented,
94753         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94754         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94755         isLiteralConstDeclaration: ts.notImplemented,
94756         getJsxFactoryEntity: ts.notImplemented,
94757         getAllAccessorDeclarations: ts.notImplemented,
94758         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94759         isBindingCapturedByNode: ts.notImplemented,
94760         getDeclarationStatementsForSourceFile: ts.notImplemented,
94761         isImportRequiredByAugmentation: ts.notImplemented,
94762     };
94763     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94764         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94765             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94766             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94767             sourceFile.text = "";
94768             sourceFile.statements = ts.createNodeArray();
94769             return sourceFile;
94770         });
94771         var jsBundle = ts.Debug.checkDefined(bundle.js);
94772         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94773             var sourceFile = sourceFiles[prologueInfo.file];
94774             sourceFile.text = prologueInfo.text;
94775             sourceFile.end = prologueInfo.text.length;
94776             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94777                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94778                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94779                 statement.expression.text = directive.expression.text;
94780                 return statement;
94781             }));
94782         });
94783         return sourceFiles;
94784     }
94785     /*@internal*/
94786     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94787         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94788         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94789         if (!buildInfoText)
94790             return buildInfoPath;
94791         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94792         if (!jsFileText)
94793             return jsFilePath;
94794         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94795         // error if no source map or for now if inline sourcemap
94796         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94797             return sourceMapFilePath || "inline sourcemap decoding";
94798         // read declaration text
94799         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94800         if (declarationFilePath && !declarationText)
94801             return declarationFilePath;
94802         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94803         // error if no source map or for now if inline sourcemap
94804         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94805             return declarationMapPath || "inline sourcemap decoding";
94806         var buildInfo = getBuildInfo(buildInfoText);
94807         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94808             return buildInfoPath;
94809         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94810         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94811         /*onlyOwnText*/ true);
94812         var outputFiles = [];
94813         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
94814         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
94815         var emitHost = {
94816             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
94817             getCanonicalFileName: host.getCanonicalFileName,
94818             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
94819             getCompilerOptions: function () { return config.options; },
94820             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
94821             getNewLine: function () { return host.getNewLine(); },
94822             getSourceFile: ts.returnUndefined,
94823             getSourceFileByPath: ts.returnUndefined,
94824             getSourceFiles: function () { return sourceFilesForJsEmit; },
94825             getLibFileFromReference: ts.notImplemented,
94826             isSourceFileFromExternalLibrary: ts.returnFalse,
94827             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
94828             getProjectReferenceRedirect: ts.returnUndefined,
94829             isSourceOfProjectReferenceRedirect: ts.returnFalse,
94830             writeFile: function (name, text, writeByteOrderMark) {
94831                 switch (name) {
94832                     case jsFilePath:
94833                         if (jsFileText === text)
94834                             return;
94835                         break;
94836                     case sourceMapFilePath:
94837                         if (sourceMapText === text)
94838                             return;
94839                         break;
94840                     case buildInfoPath:
94841                         var newBuildInfo = getBuildInfo(text);
94842                         newBuildInfo.program = buildInfo.program;
94843                         // Update sourceFileInfo
94844                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
94845                         newBuildInfo.bundle.js.sources = js.sources;
94846                         if (dts) {
94847                             newBuildInfo.bundle.dts.sources = dts.sources;
94848                         }
94849                         newBuildInfo.bundle.sourceFiles = sourceFiles;
94850                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
94851                         return;
94852                     case declarationFilePath:
94853                         if (declarationText === text)
94854                             return;
94855                         break;
94856                     case declarationMapPath:
94857                         if (declarationMapText === text)
94858                             return;
94859                         break;
94860                     default:
94861                         ts.Debug.fail("Unexpected path: " + name);
94862                 }
94863                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
94864             },
94865             isEmitBlocked: ts.returnFalse,
94866             readFile: function (f) { return host.readFile(f); },
94867             fileExists: function (f) { return host.fileExists(f); },
94868             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
94869             getProgramBuildInfo: ts.returnUndefined,
94870             getSourceFileFromReference: ts.returnUndefined,
94871             redirectTargetsMap: ts.createMultiMap()
94872         };
94873         emitFiles(ts.notImplementedResolver, emitHost, 
94874         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
94875         return outputFiles;
94876     }
94877     ts.emitUsingBuildInfo = emitUsingBuildInfo;
94878     var PipelinePhase;
94879     (function (PipelinePhase) {
94880         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
94881         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
94882         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
94883         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
94884         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
94885     })(PipelinePhase || (PipelinePhase = {}));
94886     function createPrinter(printerOptions, handlers) {
94887         if (printerOptions === void 0) { printerOptions = {}; }
94888         if (handlers === void 0) { handlers = {}; }
94889         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;
94890         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
94891         var newLine = ts.getNewLineCharacter(printerOptions);
94892         var moduleKind = ts.getEmitModuleKind(printerOptions);
94893         var bundledHelpers = ts.createMap();
94894         var currentSourceFile;
94895         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
94896         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
94897         var generatedNames; // Set of names generated by the NameGenerator.
94898         var tempFlagsStack; // Stack of enclosing name generation scopes.
94899         var tempFlags; // TempFlags for the current name generation scope.
94900         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
94901         var reservedNames; // TempFlags to reserve in nested name generation scopes.
94902         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
94903         var writer;
94904         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
94905         var write = writeBase;
94906         var isOwnFileEmit;
94907         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
94908         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
94909         var recordInternalSection = printerOptions.recordInternalSection;
94910         var sourceFileTextPos = 0;
94911         var sourceFileTextKind = "text" /* Text */;
94912         // Source Maps
94913         var sourceMapsDisabled = true;
94914         var sourceMapGenerator;
94915         var sourceMapSource;
94916         var sourceMapSourceIndex = -1;
94917         // Comments
94918         var containerPos = -1;
94919         var containerEnd = -1;
94920         var declarationListContainerEnd = -1;
94921         var currentLineMap;
94922         var detachedCommentsInfo;
94923         var hasWrittenComment = false;
94924         var commentsDisabled = !!printerOptions.removeComments;
94925         var lastNode;
94926         var lastSubstitution;
94927         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
94928         reset();
94929         return {
94930             // public API
94931             printNode: printNode,
94932             printList: printList,
94933             printFile: printFile,
94934             printBundle: printBundle,
94935             // internal API
94936             writeNode: writeNode,
94937             writeList: writeList,
94938             writeFile: writeFile,
94939             writeBundle: writeBundle,
94940             bundleFileInfo: bundleFileInfo
94941         };
94942         function printNode(hint, node, sourceFile) {
94943             switch (hint) {
94944                 case 0 /* SourceFile */:
94945                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
94946                     break;
94947                 case 2 /* IdentifierName */:
94948                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
94949                     break;
94950                 case 1 /* Expression */:
94951                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
94952                     break;
94953             }
94954             switch (node.kind) {
94955                 case 290 /* SourceFile */: return printFile(node);
94956                 case 291 /* Bundle */: return printBundle(node);
94957                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
94958             }
94959             writeNode(hint, node, sourceFile, beginPrint());
94960             return endPrint();
94961         }
94962         function printList(format, nodes, sourceFile) {
94963             writeList(format, nodes, sourceFile, beginPrint());
94964             return endPrint();
94965         }
94966         function printBundle(bundle) {
94967             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
94968             return endPrint();
94969         }
94970         function printFile(sourceFile) {
94971             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
94972             return endPrint();
94973         }
94974         function printUnparsedSource(unparsed) {
94975             writeUnparsedSource(unparsed, beginPrint());
94976             return endPrint();
94977         }
94978         function writeNode(hint, node, sourceFile, output) {
94979             var previousWriter = writer;
94980             setWriter(output, /*_sourceMapGenerator*/ undefined);
94981             print(hint, node, sourceFile);
94982             reset();
94983             writer = previousWriter;
94984         }
94985         function writeList(format, nodes, sourceFile, output) {
94986             var previousWriter = writer;
94987             setWriter(output, /*_sourceMapGenerator*/ undefined);
94988             if (sourceFile) {
94989                 setSourceFile(sourceFile);
94990             }
94991             emitList(syntheticParent, nodes, format);
94992             reset();
94993             writer = previousWriter;
94994         }
94995         function getTextPosWithWriteLine() {
94996             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
94997         }
94998         function updateOrPushBundleFileTextLike(pos, end, kind) {
94999             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95000             if (last && last.kind === kind) {
95001                 last.end = end;
95002             }
95003             else {
95004                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95005             }
95006         }
95007         function recordBundleFileInternalSectionStart(node) {
95008             if (recordInternalSection &&
95009                 bundleFileInfo &&
95010                 currentSourceFile &&
95011                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95012                 ts.isInternalDeclaration(node, currentSourceFile) &&
95013                 sourceFileTextKind !== "internal" /* Internal */) {
95014                 var prevSourceFileTextKind = sourceFileTextKind;
95015                 recordBundleFileTextLikeSection(writer.getTextPos());
95016                 sourceFileTextPos = getTextPosWithWriteLine();
95017                 sourceFileTextKind = "internal" /* Internal */;
95018                 return prevSourceFileTextKind;
95019             }
95020             return undefined;
95021         }
95022         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95023             if (prevSourceFileTextKind) {
95024                 recordBundleFileTextLikeSection(writer.getTextPos());
95025                 sourceFileTextPos = getTextPosWithWriteLine();
95026                 sourceFileTextKind = prevSourceFileTextKind;
95027             }
95028         }
95029         function recordBundleFileTextLikeSection(end) {
95030             if (sourceFileTextPos < end) {
95031                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95032                 return true;
95033             }
95034             return false;
95035         }
95036         function writeBundle(bundle, output, sourceMapGenerator) {
95037             var _a;
95038             isOwnFileEmit = false;
95039             var previousWriter = writer;
95040             setWriter(output, sourceMapGenerator);
95041             emitShebangIfNeeded(bundle);
95042             emitPrologueDirectivesIfNeeded(bundle);
95043             emitHelpers(bundle);
95044             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95045             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95046                 var prepend = _c[_b];
95047                 writeLine();
95048                 var pos = writer.getTextPos();
95049                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95050                 if (savedSections)
95051                     bundleFileInfo.sections = [];
95052                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95053                 if (bundleFileInfo) {
95054                     var newSections = bundleFileInfo.sections;
95055                     bundleFileInfo.sections = savedSections;
95056                     if (prepend.oldFileOfCurrentEmit)
95057                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95058                     else {
95059                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95060                         bundleFileInfo.sections.push({
95061                             pos: pos,
95062                             end: writer.getTextPos(),
95063                             kind: "prepend" /* Prepend */,
95064                             data: relativeToBuildInfo(prepend.fileName),
95065                             texts: newSections
95066                         });
95067                     }
95068                 }
95069             }
95070             sourceFileTextPos = getTextPosWithWriteLine();
95071             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95072                 var sourceFile = _e[_d];
95073                 print(0 /* SourceFile */, sourceFile, sourceFile);
95074             }
95075             if (bundleFileInfo && bundle.sourceFiles.length) {
95076                 var end = writer.getTextPos();
95077                 if (recordBundleFileTextLikeSection(end)) {
95078                     // Store prologues
95079                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95080                     if (prologues) {
95081                         if (!bundleFileInfo.sources)
95082                             bundleFileInfo.sources = {};
95083                         bundleFileInfo.sources.prologues = prologues;
95084                     }
95085                     // Store helpes
95086                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95087                     if (helpers) {
95088                         if (!bundleFileInfo.sources)
95089                             bundleFileInfo.sources = {};
95090                         bundleFileInfo.sources.helpers = helpers;
95091                     }
95092                 }
95093             }
95094             reset();
95095             writer = previousWriter;
95096         }
95097         function writeUnparsedSource(unparsed, output) {
95098             var previousWriter = writer;
95099             setWriter(output, /*_sourceMapGenerator*/ undefined);
95100             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95101             reset();
95102             writer = previousWriter;
95103         }
95104         function writeFile(sourceFile, output, sourceMapGenerator) {
95105             isOwnFileEmit = true;
95106             var previousWriter = writer;
95107             setWriter(output, sourceMapGenerator);
95108             emitShebangIfNeeded(sourceFile);
95109             emitPrologueDirectivesIfNeeded(sourceFile);
95110             print(0 /* SourceFile */, sourceFile, sourceFile);
95111             reset();
95112             writer = previousWriter;
95113         }
95114         function beginPrint() {
95115             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95116         }
95117         function endPrint() {
95118             var text = ownWriter.getText();
95119             ownWriter.clear();
95120             return text;
95121         }
95122         function print(hint, node, sourceFile) {
95123             if (sourceFile) {
95124                 setSourceFile(sourceFile);
95125             }
95126             pipelineEmit(hint, node);
95127         }
95128         function setSourceFile(sourceFile) {
95129             currentSourceFile = sourceFile;
95130             currentLineMap = undefined;
95131             detachedCommentsInfo = undefined;
95132             if (sourceFile) {
95133                 setSourceMapSource(sourceFile);
95134             }
95135         }
95136         function setWriter(_writer, _sourceMapGenerator) {
95137             if (_writer && printerOptions.omitTrailingSemicolon) {
95138                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95139             }
95140             writer = _writer; // TODO: GH#18217
95141             sourceMapGenerator = _sourceMapGenerator;
95142             sourceMapsDisabled = !writer || !sourceMapGenerator;
95143         }
95144         function reset() {
95145             nodeIdToGeneratedName = [];
95146             autoGeneratedIdToGeneratedName = [];
95147             generatedNames = ts.createMap();
95148             tempFlagsStack = [];
95149             tempFlags = 0 /* Auto */;
95150             reservedNamesStack = [];
95151             currentSourceFile = undefined;
95152             currentLineMap = undefined;
95153             detachedCommentsInfo = undefined;
95154             lastNode = undefined;
95155             lastSubstitution = undefined;
95156             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95157         }
95158         function getCurrentLineMap() {
95159             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95160         }
95161         function emit(node) {
95162             if (node === undefined)
95163                 return;
95164             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95165             var substitute = pipelineEmit(4 /* Unspecified */, node);
95166             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95167             return substitute;
95168         }
95169         function emitIdentifierName(node) {
95170             if (node === undefined)
95171                 return;
95172             return pipelineEmit(2 /* IdentifierName */, node);
95173         }
95174         function emitExpression(node) {
95175             if (node === undefined)
95176                 return;
95177             return pipelineEmit(1 /* Expression */, node);
95178         }
95179         function emitJsxAttributeValue(node) {
95180             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95181         }
95182         function pipelineEmit(emitHint, node) {
95183             var savedLastNode = lastNode;
95184             var savedLastSubstitution = lastSubstitution;
95185             var savedPreserveSourceNewlines = preserveSourceNewlines;
95186             lastNode = node;
95187             lastSubstitution = undefined;
95188             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95189                 preserveSourceNewlines = false;
95190             }
95191             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95192             pipelinePhase(emitHint, node);
95193             ts.Debug.assert(lastNode === node);
95194             var substitute = lastSubstitution;
95195             lastNode = savedLastNode;
95196             lastSubstitution = savedLastSubstitution;
95197             preserveSourceNewlines = savedPreserveSourceNewlines;
95198             return substitute || node;
95199         }
95200         function getPipelinePhase(phase, emitHint, node) {
95201             switch (phase) {
95202                 case 0 /* Notification */:
95203                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95204                         return pipelineEmitWithNotification;
95205                     }
95206                 // falls through
95207                 case 1 /* Substitution */:
95208                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95209                         return pipelineEmitWithSubstitution;
95210                     }
95211                 // falls through
95212                 case 2 /* Comments */:
95213                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95214                         return pipelineEmitWithComments;
95215                     }
95216                 // falls through
95217                 case 3 /* SourceMaps */:
95218                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95219                         return pipelineEmitWithSourceMap;
95220                     }
95221                 // falls through
95222                 case 4 /* Emit */:
95223                     return pipelineEmitWithHint;
95224                 default:
95225                     return ts.Debug.assertNever(phase);
95226             }
95227         }
95228         function getNextPipelinePhase(currentPhase, emitHint, node) {
95229             return getPipelinePhase(currentPhase + 1, emitHint, node);
95230         }
95231         function pipelineEmitWithNotification(hint, node) {
95232             ts.Debug.assert(lastNode === node);
95233             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95234             onEmitNode(hint, node, pipelinePhase);
95235             ts.Debug.assert(lastNode === node);
95236         }
95237         function pipelineEmitWithHint(hint, node) {
95238             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95239             if (hint === 0 /* SourceFile */)
95240                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95241             if (hint === 2 /* IdentifierName */)
95242                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95243             if (hint === 6 /* JsxAttributeValue */)
95244                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95245             if (hint === 3 /* MappedTypeParameter */)
95246                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95247             if (hint === 5 /* EmbeddedStatement */) {
95248                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95249                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95250             }
95251             if (hint === 4 /* Unspecified */) {
95252                 if (ts.isKeyword(node.kind))
95253                     return writeTokenNode(node, writeKeyword);
95254                 switch (node.kind) {
95255                     // Pseudo-literals
95256                     case 15 /* TemplateHead */:
95257                     case 16 /* TemplateMiddle */:
95258                     case 17 /* TemplateTail */:
95259                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95260                     case 292 /* UnparsedSource */:
95261                     case 286 /* UnparsedPrepend */:
95262                         return emitUnparsedSourceOrPrepend(node);
95263                     case 285 /* UnparsedPrologue */:
95264                         return writeUnparsedNode(node);
95265                     case 287 /* UnparsedText */:
95266                     case 288 /* UnparsedInternalText */:
95267                         return emitUnparsedTextLike(node);
95268                     case 289 /* UnparsedSyntheticReference */:
95269                         return emitUnparsedSyntheticReference(node);
95270                     // Identifiers
95271                     case 75 /* Identifier */:
95272                         return emitIdentifier(node);
95273                     // PrivateIdentifiers
95274                     case 76 /* PrivateIdentifier */:
95275                         return emitPrivateIdentifier(node);
95276                     // Parse tree nodes
95277                     // Names
95278                     case 153 /* QualifiedName */:
95279                         return emitQualifiedName(node);
95280                     case 154 /* ComputedPropertyName */:
95281                         return emitComputedPropertyName(node);
95282                     // Signature elements
95283                     case 155 /* TypeParameter */:
95284                         return emitTypeParameter(node);
95285                     case 156 /* Parameter */:
95286                         return emitParameter(node);
95287                     case 157 /* Decorator */:
95288                         return emitDecorator(node);
95289                     // Type members
95290                     case 158 /* PropertySignature */:
95291                         return emitPropertySignature(node);
95292                     case 159 /* PropertyDeclaration */:
95293                         return emitPropertyDeclaration(node);
95294                     case 160 /* MethodSignature */:
95295                         return emitMethodSignature(node);
95296                     case 161 /* MethodDeclaration */:
95297                         return emitMethodDeclaration(node);
95298                     case 162 /* Constructor */:
95299                         return emitConstructor(node);
95300                     case 163 /* GetAccessor */:
95301                     case 164 /* SetAccessor */:
95302                         return emitAccessorDeclaration(node);
95303                     case 165 /* CallSignature */:
95304                         return emitCallSignature(node);
95305                     case 166 /* ConstructSignature */:
95306                         return emitConstructSignature(node);
95307                     case 167 /* IndexSignature */:
95308                         return emitIndexSignature(node);
95309                     // Types
95310                     case 168 /* TypePredicate */:
95311                         return emitTypePredicate(node);
95312                     case 169 /* TypeReference */:
95313                         return emitTypeReference(node);
95314                     case 170 /* FunctionType */:
95315                         return emitFunctionType(node);
95316                     case 300 /* JSDocFunctionType */:
95317                         return emitJSDocFunctionType(node);
95318                     case 171 /* ConstructorType */:
95319                         return emitConstructorType(node);
95320                     case 172 /* TypeQuery */:
95321                         return emitTypeQuery(node);
95322                     case 173 /* TypeLiteral */:
95323                         return emitTypeLiteral(node);
95324                     case 174 /* ArrayType */:
95325                         return emitArrayType(node);
95326                     case 175 /* TupleType */:
95327                         return emitTupleType(node);
95328                     case 176 /* OptionalType */:
95329                         return emitOptionalType(node);
95330                     case 178 /* UnionType */:
95331                         return emitUnionType(node);
95332                     case 179 /* IntersectionType */:
95333                         return emitIntersectionType(node);
95334                     case 180 /* ConditionalType */:
95335                         return emitConditionalType(node);
95336                     case 181 /* InferType */:
95337                         return emitInferType(node);
95338                     case 182 /* ParenthesizedType */:
95339                         return emitParenthesizedType(node);
95340                     case 216 /* ExpressionWithTypeArguments */:
95341                         return emitExpressionWithTypeArguments(node);
95342                     case 183 /* ThisType */:
95343                         return emitThisType();
95344                     case 184 /* TypeOperator */:
95345                         return emitTypeOperator(node);
95346                     case 185 /* IndexedAccessType */:
95347                         return emitIndexedAccessType(node);
95348                     case 186 /* MappedType */:
95349                         return emitMappedType(node);
95350                     case 187 /* LiteralType */:
95351                         return emitLiteralType(node);
95352                     case 188 /* ImportType */:
95353                         return emitImportTypeNode(node);
95354                     case 295 /* JSDocAllType */:
95355                         writePunctuation("*");
95356                         return;
95357                     case 296 /* JSDocUnknownType */:
95358                         writePunctuation("?");
95359                         return;
95360                     case 297 /* JSDocNullableType */:
95361                         return emitJSDocNullableType(node);
95362                     case 298 /* JSDocNonNullableType */:
95363                         return emitJSDocNonNullableType(node);
95364                     case 299 /* JSDocOptionalType */:
95365                         return emitJSDocOptionalType(node);
95366                     case 177 /* RestType */:
95367                     case 301 /* JSDocVariadicType */:
95368                         return emitRestOrJSDocVariadicType(node);
95369                     // Binding patterns
95370                     case 189 /* ObjectBindingPattern */:
95371                         return emitObjectBindingPattern(node);
95372                     case 190 /* ArrayBindingPattern */:
95373                         return emitArrayBindingPattern(node);
95374                     case 191 /* BindingElement */:
95375                         return emitBindingElement(node);
95376                     // Misc
95377                     case 221 /* TemplateSpan */:
95378                         return emitTemplateSpan(node);
95379                     case 222 /* SemicolonClassElement */:
95380                         return emitSemicolonClassElement();
95381                     // Statements
95382                     case 223 /* Block */:
95383                         return emitBlock(node);
95384                     case 225 /* VariableStatement */:
95385                         return emitVariableStatement(node);
95386                     case 224 /* EmptyStatement */:
95387                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95388                     case 226 /* ExpressionStatement */:
95389                         return emitExpressionStatement(node);
95390                     case 227 /* IfStatement */:
95391                         return emitIfStatement(node);
95392                     case 228 /* DoStatement */:
95393                         return emitDoStatement(node);
95394                     case 229 /* WhileStatement */:
95395                         return emitWhileStatement(node);
95396                     case 230 /* ForStatement */:
95397                         return emitForStatement(node);
95398                     case 231 /* ForInStatement */:
95399                         return emitForInStatement(node);
95400                     case 232 /* ForOfStatement */:
95401                         return emitForOfStatement(node);
95402                     case 233 /* ContinueStatement */:
95403                         return emitContinueStatement(node);
95404                     case 234 /* BreakStatement */:
95405                         return emitBreakStatement(node);
95406                     case 235 /* ReturnStatement */:
95407                         return emitReturnStatement(node);
95408                     case 236 /* WithStatement */:
95409                         return emitWithStatement(node);
95410                     case 237 /* SwitchStatement */:
95411                         return emitSwitchStatement(node);
95412                     case 238 /* LabeledStatement */:
95413                         return emitLabeledStatement(node);
95414                     case 239 /* ThrowStatement */:
95415                         return emitThrowStatement(node);
95416                     case 240 /* TryStatement */:
95417                         return emitTryStatement(node);
95418                     case 241 /* DebuggerStatement */:
95419                         return emitDebuggerStatement(node);
95420                     // Declarations
95421                     case 242 /* VariableDeclaration */:
95422                         return emitVariableDeclaration(node);
95423                     case 243 /* VariableDeclarationList */:
95424                         return emitVariableDeclarationList(node);
95425                     case 244 /* FunctionDeclaration */:
95426                         return emitFunctionDeclaration(node);
95427                     case 245 /* ClassDeclaration */:
95428                         return emitClassDeclaration(node);
95429                     case 246 /* InterfaceDeclaration */:
95430                         return emitInterfaceDeclaration(node);
95431                     case 247 /* TypeAliasDeclaration */:
95432                         return emitTypeAliasDeclaration(node);
95433                     case 248 /* EnumDeclaration */:
95434                         return emitEnumDeclaration(node);
95435                     case 249 /* ModuleDeclaration */:
95436                         return emitModuleDeclaration(node);
95437                     case 250 /* ModuleBlock */:
95438                         return emitModuleBlock(node);
95439                     case 251 /* CaseBlock */:
95440                         return emitCaseBlock(node);
95441                     case 252 /* NamespaceExportDeclaration */:
95442                         return emitNamespaceExportDeclaration(node);
95443                     case 253 /* ImportEqualsDeclaration */:
95444                         return emitImportEqualsDeclaration(node);
95445                     case 254 /* ImportDeclaration */:
95446                         return emitImportDeclaration(node);
95447                     case 255 /* ImportClause */:
95448                         return emitImportClause(node);
95449                     case 256 /* NamespaceImport */:
95450                         return emitNamespaceImport(node);
95451                     case 262 /* NamespaceExport */:
95452                         return emitNamespaceExport(node);
95453                     case 257 /* NamedImports */:
95454                         return emitNamedImports(node);
95455                     case 258 /* ImportSpecifier */:
95456                         return emitImportSpecifier(node);
95457                     case 259 /* ExportAssignment */:
95458                         return emitExportAssignment(node);
95459                     case 260 /* ExportDeclaration */:
95460                         return emitExportDeclaration(node);
95461                     case 261 /* NamedExports */:
95462                         return emitNamedExports(node);
95463                     case 263 /* ExportSpecifier */:
95464                         return emitExportSpecifier(node);
95465                     case 264 /* MissingDeclaration */:
95466                         return;
95467                     // Module references
95468                     case 265 /* ExternalModuleReference */:
95469                         return emitExternalModuleReference(node);
95470                     // JSX (non-expression)
95471                     case 11 /* JsxText */:
95472                         return emitJsxText(node);
95473                     case 268 /* JsxOpeningElement */:
95474                     case 271 /* JsxOpeningFragment */:
95475                         return emitJsxOpeningElementOrFragment(node);
95476                     case 269 /* JsxClosingElement */:
95477                     case 272 /* JsxClosingFragment */:
95478                         return emitJsxClosingElementOrFragment(node);
95479                     case 273 /* JsxAttribute */:
95480                         return emitJsxAttribute(node);
95481                     case 274 /* JsxAttributes */:
95482                         return emitJsxAttributes(node);
95483                     case 275 /* JsxSpreadAttribute */:
95484                         return emitJsxSpreadAttribute(node);
95485                     case 276 /* JsxExpression */:
95486                         return emitJsxExpression(node);
95487                     // Clauses
95488                     case 277 /* CaseClause */:
95489                         return emitCaseClause(node);
95490                     case 278 /* DefaultClause */:
95491                         return emitDefaultClause(node);
95492                     case 279 /* HeritageClause */:
95493                         return emitHeritageClause(node);
95494                     case 280 /* CatchClause */:
95495                         return emitCatchClause(node);
95496                     // Property assignments
95497                     case 281 /* PropertyAssignment */:
95498                         return emitPropertyAssignment(node);
95499                     case 282 /* ShorthandPropertyAssignment */:
95500                         return emitShorthandPropertyAssignment(node);
95501                     case 283 /* SpreadAssignment */:
95502                         return emitSpreadAssignment(node);
95503                     // Enum
95504                     case 284 /* EnumMember */:
95505                         return emitEnumMember(node);
95506                     // JSDoc nodes (only used in codefixes currently)
95507                     case 317 /* JSDocParameterTag */:
95508                     case 323 /* JSDocPropertyTag */:
95509                         return emitJSDocPropertyLikeTag(node);
95510                     case 318 /* JSDocReturnTag */:
95511                     case 320 /* JSDocTypeTag */:
95512                     case 319 /* JSDocThisTag */:
95513                     case 316 /* JSDocEnumTag */:
95514                         return emitJSDocSimpleTypedTag(node);
95515                     case 308 /* JSDocImplementsTag */:
95516                     case 307 /* JSDocAugmentsTag */:
95517                         return emitJSDocHeritageTag(node);
95518                     case 321 /* JSDocTemplateTag */:
95519                         return emitJSDocTemplateTag(node);
95520                     case 322 /* JSDocTypedefTag */:
95521                         return emitJSDocTypedefTag(node);
95522                     case 315 /* JSDocCallbackTag */:
95523                         return emitJSDocCallbackTag(node);
95524                     case 305 /* JSDocSignature */:
95525                         return emitJSDocSignature(node);
95526                     case 304 /* JSDocTypeLiteral */:
95527                         return emitJSDocTypeLiteral(node);
95528                     case 310 /* JSDocClassTag */:
95529                     case 306 /* JSDocTag */:
95530                         return emitJSDocSimpleTag(node);
95531                     case 303 /* JSDocComment */:
95532                         return emitJSDoc(node);
95533                     // Transformation nodes (ignored)
95534                 }
95535                 if (ts.isExpression(node)) {
95536                     hint = 1 /* Expression */;
95537                     if (substituteNode !== ts.noEmitSubstitution) {
95538                         lastSubstitution = node = substituteNode(hint, node);
95539                     }
95540                 }
95541                 else if (ts.isToken(node)) {
95542                     return writeTokenNode(node, writePunctuation);
95543                 }
95544             }
95545             if (hint === 1 /* Expression */) {
95546                 switch (node.kind) {
95547                     // Literals
95548                     case 8 /* NumericLiteral */:
95549                     case 9 /* BigIntLiteral */:
95550                         return emitNumericOrBigIntLiteral(node);
95551                     case 10 /* StringLiteral */:
95552                     case 13 /* RegularExpressionLiteral */:
95553                     case 14 /* NoSubstitutionTemplateLiteral */:
95554                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95555                     // Identifiers
95556                     case 75 /* Identifier */:
95557                         return emitIdentifier(node);
95558                     // Reserved words
95559                     case 91 /* FalseKeyword */:
95560                     case 100 /* NullKeyword */:
95561                     case 102 /* SuperKeyword */:
95562                     case 106 /* TrueKeyword */:
95563                     case 104 /* ThisKeyword */:
95564                     case 96 /* ImportKeyword */:
95565                         writeTokenNode(node, writeKeyword);
95566                         return;
95567                     // Expressions
95568                     case 192 /* ArrayLiteralExpression */:
95569                         return emitArrayLiteralExpression(node);
95570                     case 193 /* ObjectLiteralExpression */:
95571                         return emitObjectLiteralExpression(node);
95572                     case 194 /* PropertyAccessExpression */:
95573                         return emitPropertyAccessExpression(node);
95574                     case 195 /* ElementAccessExpression */:
95575                         return emitElementAccessExpression(node);
95576                     case 196 /* CallExpression */:
95577                         return emitCallExpression(node);
95578                     case 197 /* NewExpression */:
95579                         return emitNewExpression(node);
95580                     case 198 /* TaggedTemplateExpression */:
95581                         return emitTaggedTemplateExpression(node);
95582                     case 199 /* TypeAssertionExpression */:
95583                         return emitTypeAssertionExpression(node);
95584                     case 200 /* ParenthesizedExpression */:
95585                         return emitParenthesizedExpression(node);
95586                     case 201 /* FunctionExpression */:
95587                         return emitFunctionExpression(node);
95588                     case 202 /* ArrowFunction */:
95589                         return emitArrowFunction(node);
95590                     case 203 /* DeleteExpression */:
95591                         return emitDeleteExpression(node);
95592                     case 204 /* TypeOfExpression */:
95593                         return emitTypeOfExpression(node);
95594                     case 205 /* VoidExpression */:
95595                         return emitVoidExpression(node);
95596                     case 206 /* AwaitExpression */:
95597                         return emitAwaitExpression(node);
95598                     case 207 /* PrefixUnaryExpression */:
95599                         return emitPrefixUnaryExpression(node);
95600                     case 208 /* PostfixUnaryExpression */:
95601                         return emitPostfixUnaryExpression(node);
95602                     case 209 /* BinaryExpression */:
95603                         return emitBinaryExpression(node);
95604                     case 210 /* ConditionalExpression */:
95605                         return emitConditionalExpression(node);
95606                     case 211 /* TemplateExpression */:
95607                         return emitTemplateExpression(node);
95608                     case 212 /* YieldExpression */:
95609                         return emitYieldExpression(node);
95610                     case 213 /* SpreadElement */:
95611                         return emitSpreadExpression(node);
95612                     case 214 /* ClassExpression */:
95613                         return emitClassExpression(node);
95614                     case 215 /* OmittedExpression */:
95615                         return;
95616                     case 217 /* AsExpression */:
95617                         return emitAsExpression(node);
95618                     case 218 /* NonNullExpression */:
95619                         return emitNonNullExpression(node);
95620                     case 219 /* MetaProperty */:
95621                         return emitMetaProperty(node);
95622                     // JSX
95623                     case 266 /* JsxElement */:
95624                         return emitJsxElement(node);
95625                     case 267 /* JsxSelfClosingElement */:
95626                         return emitJsxSelfClosingElement(node);
95627                     case 270 /* JsxFragment */:
95628                         return emitJsxFragment(node);
95629                     // Transformation nodes
95630                     case 326 /* PartiallyEmittedExpression */:
95631                         return emitPartiallyEmittedExpression(node);
95632                     case 327 /* CommaListExpression */:
95633                         return emitCommaList(node);
95634                 }
95635             }
95636         }
95637         function emitMappedTypeParameter(node) {
95638             emit(node.name);
95639             writeSpace();
95640             writeKeyword("in");
95641             writeSpace();
95642             emit(node.constraint);
95643         }
95644         function pipelineEmitWithSubstitution(hint, node) {
95645             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95646             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95647             pipelinePhase(hint, lastSubstitution);
95648             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95649         }
95650         function getHelpersFromBundledSourceFiles(bundle) {
95651             var result;
95652             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95653                 return undefined;
95654             }
95655             var bundledHelpers = ts.createMap();
95656             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95657                 var sourceFile = _b[_a];
95658                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95659                 var helpers = getSortedEmitHelpers(sourceFile);
95660                 if (!helpers)
95661                     continue;
95662                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95663                     var helper = helpers_4[_c];
95664                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95665                         bundledHelpers.set(helper.name, true);
95666                         (result || (result = [])).push(helper.name);
95667                     }
95668                 }
95669             }
95670             return result;
95671         }
95672         function emitHelpers(node) {
95673             var helpersEmitted = false;
95674             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95675             if (bundle && moduleKind === ts.ModuleKind.None) {
95676                 return;
95677             }
95678             var numPrepends = bundle ? bundle.prepends.length : 0;
95679             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95680             for (var i = 0; i < numNodes; i++) {
95681                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95682                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95683                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95684                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95685                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95686                 if (helpers) {
95687                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95688                         var helper = helpers_5[_a];
95689                         if (!helper.scoped) {
95690                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95691                             // option is set, or if it can be imported and the importHelpers compiler
95692                             // option is set.
95693                             if (shouldSkip)
95694                                 continue;
95695                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95696                             // are emitting a bundled module.
95697                             if (shouldBundle) {
95698                                 if (bundledHelpers.get(helper.name)) {
95699                                     continue;
95700                                 }
95701                                 bundledHelpers.set(helper.name, true);
95702                             }
95703                         }
95704                         else if (bundle) {
95705                             // Skip the helper if it is scoped and we are emitting bundled helpers
95706                             continue;
95707                         }
95708                         var pos = getTextPosWithWriteLine();
95709                         if (typeof helper.text === "string") {
95710                             writeLines(helper.text);
95711                         }
95712                         else {
95713                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95714                         }
95715                         if (bundleFileInfo)
95716                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95717                         helpersEmitted = true;
95718                     }
95719                 }
95720             }
95721             return helpersEmitted;
95722         }
95723         function getSortedEmitHelpers(node) {
95724             var helpers = ts.getEmitHelpers(node);
95725             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95726         }
95727         //
95728         // Literals/Pseudo-literals
95729         //
95730         // SyntaxKind.NumericLiteral
95731         // SyntaxKind.BigIntLiteral
95732         function emitNumericOrBigIntLiteral(node) {
95733             emitLiteral(node, /*jsxAttributeEscape*/ false);
95734         }
95735         // SyntaxKind.StringLiteral
95736         // SyntaxKind.RegularExpressionLiteral
95737         // SyntaxKind.NoSubstitutionTemplateLiteral
95738         // SyntaxKind.TemplateHead
95739         // SyntaxKind.TemplateMiddle
95740         // SyntaxKind.TemplateTail
95741         function emitLiteral(node, jsxAttributeEscape) {
95742             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95743             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95744                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95745                 writeLiteral(text);
95746             }
95747             else {
95748                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95749                 writeStringLiteral(text);
95750             }
95751         }
95752         // SyntaxKind.UnparsedSource
95753         // SyntaxKind.UnparsedPrepend
95754         function emitUnparsedSourceOrPrepend(unparsed) {
95755             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95756                 var text = _b[_a];
95757                 writeLine();
95758                 emit(text);
95759             }
95760         }
95761         // SyntaxKind.UnparsedPrologue
95762         // SyntaxKind.UnparsedText
95763         // SyntaxKind.UnparsedInternal
95764         // SyntaxKind.UnparsedSyntheticReference
95765         function writeUnparsedNode(unparsed) {
95766             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95767         }
95768         // SyntaxKind.UnparsedText
95769         // SyntaxKind.UnparsedInternal
95770         function emitUnparsedTextLike(unparsed) {
95771             var pos = getTextPosWithWriteLine();
95772             writeUnparsedNode(unparsed);
95773             if (bundleFileInfo) {
95774                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95775                     "text" /* Text */ :
95776                     "internal" /* Internal */);
95777             }
95778         }
95779         // SyntaxKind.UnparsedSyntheticReference
95780         function emitUnparsedSyntheticReference(unparsed) {
95781             var pos = getTextPosWithWriteLine();
95782             writeUnparsedNode(unparsed);
95783             if (bundleFileInfo) {
95784                 var section = ts.clone(unparsed.section);
95785                 section.pos = pos;
95786                 section.end = writer.getTextPos();
95787                 bundleFileInfo.sections.push(section);
95788             }
95789         }
95790         //
95791         // Identifiers
95792         //
95793         function emitIdentifier(node) {
95794             var writeText = node.symbol ? writeSymbol : write;
95795             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95796             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95797         }
95798         //
95799         // Names
95800         //
95801         function emitPrivateIdentifier(node) {
95802             var writeText = node.symbol ? writeSymbol : write;
95803             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95804         }
95805         function emitQualifiedName(node) {
95806             emitEntityName(node.left);
95807             writePunctuation(".");
95808             emit(node.right);
95809         }
95810         function emitEntityName(node) {
95811             if (node.kind === 75 /* Identifier */) {
95812                 emitExpression(node);
95813             }
95814             else {
95815                 emit(node);
95816             }
95817         }
95818         function emitComputedPropertyName(node) {
95819             writePunctuation("[");
95820             emitExpression(node.expression);
95821             writePunctuation("]");
95822         }
95823         //
95824         // Signature elements
95825         //
95826         function emitTypeParameter(node) {
95827             emit(node.name);
95828             if (node.constraint) {
95829                 writeSpace();
95830                 writeKeyword("extends");
95831                 writeSpace();
95832                 emit(node.constraint);
95833             }
95834             if (node.default) {
95835                 writeSpace();
95836                 writeOperator("=");
95837                 writeSpace();
95838                 emit(node.default);
95839             }
95840         }
95841         function emitParameter(node) {
95842             emitDecorators(node, node.decorators);
95843             emitModifiers(node, node.modifiers);
95844             emit(node.dotDotDotToken);
95845             emitNodeWithWriter(node.name, writeParameter);
95846             emit(node.questionToken);
95847             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
95848                 emit(node.type);
95849             }
95850             else {
95851                 emitTypeAnnotation(node.type);
95852             }
95853             // 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.
95854             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);
95855         }
95856         function emitDecorator(decorator) {
95857             writePunctuation("@");
95858             emitExpression(decorator.expression);
95859         }
95860         //
95861         // Type members
95862         //
95863         function emitPropertySignature(node) {
95864             emitDecorators(node, node.decorators);
95865             emitModifiers(node, node.modifiers);
95866             emitNodeWithWriter(node.name, writeProperty);
95867             emit(node.questionToken);
95868             emitTypeAnnotation(node.type);
95869             writeTrailingSemicolon();
95870         }
95871         function emitPropertyDeclaration(node) {
95872             emitDecorators(node, node.decorators);
95873             emitModifiers(node, node.modifiers);
95874             emit(node.name);
95875             emit(node.questionToken);
95876             emit(node.exclamationToken);
95877             emitTypeAnnotation(node.type);
95878             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
95879             writeTrailingSemicolon();
95880         }
95881         function emitMethodSignature(node) {
95882             pushNameGenerationScope(node);
95883             emitDecorators(node, node.decorators);
95884             emitModifiers(node, node.modifiers);
95885             emit(node.name);
95886             emit(node.questionToken);
95887             emitTypeParameters(node, node.typeParameters);
95888             emitParameters(node, node.parameters);
95889             emitTypeAnnotation(node.type);
95890             writeTrailingSemicolon();
95891             popNameGenerationScope(node);
95892         }
95893         function emitMethodDeclaration(node) {
95894             emitDecorators(node, node.decorators);
95895             emitModifiers(node, node.modifiers);
95896             emit(node.asteriskToken);
95897             emit(node.name);
95898             emit(node.questionToken);
95899             emitSignatureAndBody(node, emitSignatureHead);
95900         }
95901         function emitConstructor(node) {
95902             emitModifiers(node, node.modifiers);
95903             writeKeyword("constructor");
95904             emitSignatureAndBody(node, emitSignatureHead);
95905         }
95906         function emitAccessorDeclaration(node) {
95907             emitDecorators(node, node.decorators);
95908             emitModifiers(node, node.modifiers);
95909             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
95910             writeSpace();
95911             emit(node.name);
95912             emitSignatureAndBody(node, emitSignatureHead);
95913         }
95914         function emitCallSignature(node) {
95915             pushNameGenerationScope(node);
95916             emitDecorators(node, node.decorators);
95917             emitModifiers(node, node.modifiers);
95918             emitTypeParameters(node, node.typeParameters);
95919             emitParameters(node, node.parameters);
95920             emitTypeAnnotation(node.type);
95921             writeTrailingSemicolon();
95922             popNameGenerationScope(node);
95923         }
95924         function emitConstructSignature(node) {
95925             pushNameGenerationScope(node);
95926             emitDecorators(node, node.decorators);
95927             emitModifiers(node, node.modifiers);
95928             writeKeyword("new");
95929             writeSpace();
95930             emitTypeParameters(node, node.typeParameters);
95931             emitParameters(node, node.parameters);
95932             emitTypeAnnotation(node.type);
95933             writeTrailingSemicolon();
95934             popNameGenerationScope(node);
95935         }
95936         function emitIndexSignature(node) {
95937             emitDecorators(node, node.decorators);
95938             emitModifiers(node, node.modifiers);
95939             emitParametersForIndexSignature(node, node.parameters);
95940             emitTypeAnnotation(node.type);
95941             writeTrailingSemicolon();
95942         }
95943         function emitSemicolonClassElement() {
95944             writeTrailingSemicolon();
95945         }
95946         //
95947         // Types
95948         //
95949         function emitTypePredicate(node) {
95950             if (node.assertsModifier) {
95951                 emit(node.assertsModifier);
95952                 writeSpace();
95953             }
95954             emit(node.parameterName);
95955             if (node.type) {
95956                 writeSpace();
95957                 writeKeyword("is");
95958                 writeSpace();
95959                 emit(node.type);
95960             }
95961         }
95962         function emitTypeReference(node) {
95963             emit(node.typeName);
95964             emitTypeArguments(node, node.typeArguments);
95965         }
95966         function emitFunctionType(node) {
95967             pushNameGenerationScope(node);
95968             emitTypeParameters(node, node.typeParameters);
95969             emitParametersForArrow(node, node.parameters);
95970             writeSpace();
95971             writePunctuation("=>");
95972             writeSpace();
95973             emit(node.type);
95974             popNameGenerationScope(node);
95975         }
95976         function emitJSDocFunctionType(node) {
95977             writeKeyword("function");
95978             emitParameters(node, node.parameters);
95979             writePunctuation(":");
95980             emit(node.type);
95981         }
95982         function emitJSDocNullableType(node) {
95983             writePunctuation("?");
95984             emit(node.type);
95985         }
95986         function emitJSDocNonNullableType(node) {
95987             writePunctuation("!");
95988             emit(node.type);
95989         }
95990         function emitJSDocOptionalType(node) {
95991             emit(node.type);
95992             writePunctuation("=");
95993         }
95994         function emitConstructorType(node) {
95995             pushNameGenerationScope(node);
95996             writeKeyword("new");
95997             writeSpace();
95998             emitTypeParameters(node, node.typeParameters);
95999             emitParameters(node, node.parameters);
96000             writeSpace();
96001             writePunctuation("=>");
96002             writeSpace();
96003             emit(node.type);
96004             popNameGenerationScope(node);
96005         }
96006         function emitTypeQuery(node) {
96007             writeKeyword("typeof");
96008             writeSpace();
96009             emit(node.exprName);
96010         }
96011         function emitTypeLiteral(node) {
96012             writePunctuation("{");
96013             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96014             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96015             writePunctuation("}");
96016         }
96017         function emitArrayType(node) {
96018             emit(node.elementType);
96019             writePunctuation("[");
96020             writePunctuation("]");
96021         }
96022         function emitRestOrJSDocVariadicType(node) {
96023             writePunctuation("...");
96024             emit(node.type);
96025         }
96026         function emitTupleType(node) {
96027             writePunctuation("[");
96028             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96029             writePunctuation("]");
96030         }
96031         function emitOptionalType(node) {
96032             emit(node.type);
96033             writePunctuation("?");
96034         }
96035         function emitUnionType(node) {
96036             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96037         }
96038         function emitIntersectionType(node) {
96039             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96040         }
96041         function emitConditionalType(node) {
96042             emit(node.checkType);
96043             writeSpace();
96044             writeKeyword("extends");
96045             writeSpace();
96046             emit(node.extendsType);
96047             writeSpace();
96048             writePunctuation("?");
96049             writeSpace();
96050             emit(node.trueType);
96051             writeSpace();
96052             writePunctuation(":");
96053             writeSpace();
96054             emit(node.falseType);
96055         }
96056         function emitInferType(node) {
96057             writeKeyword("infer");
96058             writeSpace();
96059             emit(node.typeParameter);
96060         }
96061         function emitParenthesizedType(node) {
96062             writePunctuation("(");
96063             emit(node.type);
96064             writePunctuation(")");
96065         }
96066         function emitThisType() {
96067             writeKeyword("this");
96068         }
96069         function emitTypeOperator(node) {
96070             writeTokenText(node.operator, writeKeyword);
96071             writeSpace();
96072             emit(node.type);
96073         }
96074         function emitIndexedAccessType(node) {
96075             emit(node.objectType);
96076             writePunctuation("[");
96077             emit(node.indexType);
96078             writePunctuation("]");
96079         }
96080         function emitMappedType(node) {
96081             var emitFlags = ts.getEmitFlags(node);
96082             writePunctuation("{");
96083             if (emitFlags & 1 /* SingleLine */) {
96084                 writeSpace();
96085             }
96086             else {
96087                 writeLine();
96088                 increaseIndent();
96089             }
96090             if (node.readonlyToken) {
96091                 emit(node.readonlyToken);
96092                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96093                     writeKeyword("readonly");
96094                 }
96095                 writeSpace();
96096             }
96097             writePunctuation("[");
96098             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96099             writePunctuation("]");
96100             if (node.questionToken) {
96101                 emit(node.questionToken);
96102                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96103                     writePunctuation("?");
96104                 }
96105             }
96106             writePunctuation(":");
96107             writeSpace();
96108             emit(node.type);
96109             writeTrailingSemicolon();
96110             if (emitFlags & 1 /* SingleLine */) {
96111                 writeSpace();
96112             }
96113             else {
96114                 writeLine();
96115                 decreaseIndent();
96116             }
96117             writePunctuation("}");
96118         }
96119         function emitLiteralType(node) {
96120             emitExpression(node.literal);
96121         }
96122         function emitImportTypeNode(node) {
96123             if (node.isTypeOf) {
96124                 writeKeyword("typeof");
96125                 writeSpace();
96126             }
96127             writeKeyword("import");
96128             writePunctuation("(");
96129             emit(node.argument);
96130             writePunctuation(")");
96131             if (node.qualifier) {
96132                 writePunctuation(".");
96133                 emit(node.qualifier);
96134             }
96135             emitTypeArguments(node, node.typeArguments);
96136         }
96137         //
96138         // Binding patterns
96139         //
96140         function emitObjectBindingPattern(node) {
96141             writePunctuation("{");
96142             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96143             writePunctuation("}");
96144         }
96145         function emitArrayBindingPattern(node) {
96146             writePunctuation("[");
96147             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96148             writePunctuation("]");
96149         }
96150         function emitBindingElement(node) {
96151             emit(node.dotDotDotToken);
96152             if (node.propertyName) {
96153                 emit(node.propertyName);
96154                 writePunctuation(":");
96155                 writeSpace();
96156             }
96157             emit(node.name);
96158             emitInitializer(node.initializer, node.name.end, node);
96159         }
96160         //
96161         // Expressions
96162         //
96163         function emitArrayLiteralExpression(node) {
96164             var elements = node.elements;
96165             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96166             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96167         }
96168         function emitObjectLiteralExpression(node) {
96169             ts.forEach(node.properties, generateMemberNames);
96170             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96171             if (indentedFlag) {
96172                 increaseIndent();
96173             }
96174             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96175             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96176             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96177             if (indentedFlag) {
96178                 decreaseIndent();
96179             }
96180         }
96181         function emitPropertyAccessExpression(node) {
96182             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96183             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96184             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96185             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96186             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96187             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96188                 mayNeedDotDotForPropertyAccess(expression) &&
96189                 !writer.hasTrailingComment() &&
96190                 !writer.hasTrailingWhitespace();
96191             if (shouldEmitDotDot) {
96192                 writePunctuation(".");
96193             }
96194             if (node.questionDotToken) {
96195                 emit(token);
96196             }
96197             else {
96198                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96199             }
96200             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96201             emit(node.name);
96202             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96203         }
96204         // 1..toString is a valid property access, emit a dot after the literal
96205         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96206         function mayNeedDotDotForPropertyAccess(expression) {
96207             expression = ts.skipPartiallyEmittedExpressions(expression);
96208             if (ts.isNumericLiteral(expression)) {
96209                 // check if numeric literal is a decimal literal that was originally written with a dot
96210                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96211                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96212                 // if the expression doesn't have any comments that will be emitted.
96213                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96214             }
96215             else if (ts.isAccessExpression(expression)) {
96216                 // check if constant enum value is integer
96217                 var constantValue = ts.getConstantValue(expression);
96218                 // isFinite handles cases when constantValue is undefined
96219                 return typeof constantValue === "number" && isFinite(constantValue)
96220                     && Math.floor(constantValue) === constantValue;
96221             }
96222         }
96223         function emitElementAccessExpression(node) {
96224             emitExpression(node.expression);
96225             emit(node.questionDotToken);
96226             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96227             emitExpression(node.argumentExpression);
96228             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96229         }
96230         function emitCallExpression(node) {
96231             emitExpression(node.expression);
96232             emit(node.questionDotToken);
96233             emitTypeArguments(node, node.typeArguments);
96234             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96235         }
96236         function emitNewExpression(node) {
96237             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96238             writeSpace();
96239             emitExpression(node.expression);
96240             emitTypeArguments(node, node.typeArguments);
96241             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96242         }
96243         function emitTaggedTemplateExpression(node) {
96244             emitExpression(node.tag);
96245             emitTypeArguments(node, node.typeArguments);
96246             writeSpace();
96247             emitExpression(node.template);
96248         }
96249         function emitTypeAssertionExpression(node) {
96250             writePunctuation("<");
96251             emit(node.type);
96252             writePunctuation(">");
96253             emitExpression(node.expression);
96254         }
96255         function emitParenthesizedExpression(node) {
96256             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96257             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96258             emitExpression(node.expression);
96259             writeLineSeparatorsAfter(node.expression, node);
96260             decreaseIndentIf(indented);
96261             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96262         }
96263         function emitFunctionExpression(node) {
96264             generateNameIfNeeded(node.name);
96265             emitFunctionDeclarationOrExpression(node);
96266         }
96267         function emitArrowFunction(node) {
96268             emitDecorators(node, node.decorators);
96269             emitModifiers(node, node.modifiers);
96270             emitSignatureAndBody(node, emitArrowFunctionHead);
96271         }
96272         function emitArrowFunctionHead(node) {
96273             emitTypeParameters(node, node.typeParameters);
96274             emitParametersForArrow(node, node.parameters);
96275             emitTypeAnnotation(node.type);
96276             writeSpace();
96277             emit(node.equalsGreaterThanToken);
96278         }
96279         function emitDeleteExpression(node) {
96280             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96281             writeSpace();
96282             emitExpression(node.expression);
96283         }
96284         function emitTypeOfExpression(node) {
96285             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96286             writeSpace();
96287             emitExpression(node.expression);
96288         }
96289         function emitVoidExpression(node) {
96290             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96291             writeSpace();
96292             emitExpression(node.expression);
96293         }
96294         function emitAwaitExpression(node) {
96295             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96296             writeSpace();
96297             emitExpression(node.expression);
96298         }
96299         function emitPrefixUnaryExpression(node) {
96300             writeTokenText(node.operator, writeOperator);
96301             if (shouldEmitWhitespaceBeforeOperand(node)) {
96302                 writeSpace();
96303             }
96304             emitExpression(node.operand);
96305         }
96306         function shouldEmitWhitespaceBeforeOperand(node) {
96307             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96308             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96309             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96310             // are just for clarity of exposition, and not part of the source code):
96311             //
96312             //  (+(+1))
96313             //  (+(++1))
96314             //
96315             // We need to emit a space in both cases. In the first case, the absence of a space will make
96316             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96317             // expression a prefix increment whose operand is a plus expression - (++(+x))
96318             // The same is true of minus of course.
96319             var operand = node.operand;
96320             return operand.kind === 207 /* PrefixUnaryExpression */
96321                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96322                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96323         }
96324         function emitPostfixUnaryExpression(node) {
96325             emitExpression(node.operand);
96326             writeTokenText(node.operator, writeOperator);
96327         }
96328         var EmitBinaryExpressionState;
96329         (function (EmitBinaryExpressionState) {
96330             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96331             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96332             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96333         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96334         /**
96335          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96336          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96337          * not require notification/substitution/comment/sourcemap decorations.
96338          */
96339         function emitBinaryExpression(node) {
96340             var nodeStack = [node];
96341             var stateStack = [0 /* EmitLeft */];
96342             var stackIndex = 0;
96343             while (stackIndex >= 0) {
96344                 node = nodeStack[stackIndex];
96345                 switch (stateStack[stackIndex]) {
96346                     case 0 /* EmitLeft */: {
96347                         maybePipelineEmitExpression(node.left);
96348                         break;
96349                     }
96350                     case 1 /* EmitRight */: {
96351                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96352                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96353                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96354                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96355                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96356                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96357                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96358                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96359                         maybePipelineEmitExpression(node.right);
96360                         break;
96361                     }
96362                     case 2 /* FinishEmit */: {
96363                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96364                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96365                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96366                         stackIndex--;
96367                         break;
96368                     }
96369                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96370                 }
96371             }
96372             function maybePipelineEmitExpression(next) {
96373                 // Advance the state of this unit of work,
96374                 stateStack[stackIndex]++;
96375                 // Then actually do the work of emitting the node `next` returned by the prior state
96376                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96377                 // binary expression handling, where possible, to the contained work queue
96378                 // #region trampolinePipelineEmit
96379                 var savedLastNode = lastNode;
96380                 var savedLastSubstitution = lastSubstitution;
96381                 lastNode = next;
96382                 lastSubstitution = undefined;
96383                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96384                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96385                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96386                     // skip all the intermediate indirection and push the expression directly onto the work stack
96387                     stackIndex++;
96388                     stateStack[stackIndex] = 0 /* EmitLeft */;
96389                     nodeStack[stackIndex] = next;
96390                 }
96391                 else {
96392                     pipelinePhase(1 /* Expression */, next);
96393                 }
96394                 ts.Debug.assert(lastNode === next);
96395                 lastNode = savedLastNode;
96396                 lastSubstitution = savedLastSubstitution;
96397                 // #endregion trampolinePipelineEmit
96398             }
96399         }
96400         function emitConditionalExpression(node) {
96401             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96402             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96403             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96404             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96405             emitExpression(node.condition);
96406             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96407             emit(node.questionToken);
96408             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96409             emitExpression(node.whenTrue);
96410             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96411             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96412             emit(node.colonToken);
96413             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96414             emitExpression(node.whenFalse);
96415             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96416         }
96417         function emitTemplateExpression(node) {
96418             emit(node.head);
96419             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96420         }
96421         function emitYieldExpression(node) {
96422             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96423             emit(node.asteriskToken);
96424             emitExpressionWithLeadingSpace(node.expression);
96425         }
96426         function emitSpreadExpression(node) {
96427             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96428             emitExpression(node.expression);
96429         }
96430         function emitClassExpression(node) {
96431             generateNameIfNeeded(node.name);
96432             emitClassDeclarationOrExpression(node);
96433         }
96434         function emitExpressionWithTypeArguments(node) {
96435             emitExpression(node.expression);
96436             emitTypeArguments(node, node.typeArguments);
96437         }
96438         function emitAsExpression(node) {
96439             emitExpression(node.expression);
96440             if (node.type) {
96441                 writeSpace();
96442                 writeKeyword("as");
96443                 writeSpace();
96444                 emit(node.type);
96445             }
96446         }
96447         function emitNonNullExpression(node) {
96448             emitExpression(node.expression);
96449             writeOperator("!");
96450         }
96451         function emitMetaProperty(node) {
96452             writeToken(node.keywordToken, node.pos, writePunctuation);
96453             writePunctuation(".");
96454             emit(node.name);
96455         }
96456         //
96457         // Misc
96458         //
96459         function emitTemplateSpan(node) {
96460             emitExpression(node.expression);
96461             emit(node.literal);
96462         }
96463         //
96464         // Statements
96465         //
96466         function emitBlock(node) {
96467             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96468         }
96469         function emitBlockStatements(node, forceSingleLine) {
96470             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96471             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96472             emitList(node, node.statements, format);
96473             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96474         }
96475         function emitVariableStatement(node) {
96476             emitModifiers(node, node.modifiers);
96477             emit(node.declarationList);
96478             writeTrailingSemicolon();
96479         }
96480         function emitEmptyStatement(isEmbeddedStatement) {
96481             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96482             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96483             if (isEmbeddedStatement) {
96484                 writePunctuation(";");
96485             }
96486             else {
96487                 writeTrailingSemicolon();
96488             }
96489         }
96490         function emitExpressionStatement(node) {
96491             emitExpression(node.expression);
96492             // Emit semicolon in non json files
96493             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96494             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96495                 writeTrailingSemicolon();
96496             }
96497         }
96498         function emitIfStatement(node) {
96499             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96500             writeSpace();
96501             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96502             emitExpression(node.expression);
96503             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96504             emitEmbeddedStatement(node, node.thenStatement);
96505             if (node.elseStatement) {
96506                 writeLineOrSpace(node);
96507                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96508                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96509                     writeSpace();
96510                     emit(node.elseStatement);
96511                 }
96512                 else {
96513                     emitEmbeddedStatement(node, node.elseStatement);
96514                 }
96515             }
96516         }
96517         function emitWhileClause(node, startPos) {
96518             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96519             writeSpace();
96520             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96521             emitExpression(node.expression);
96522             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96523         }
96524         function emitDoStatement(node) {
96525             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96526             emitEmbeddedStatement(node, node.statement);
96527             if (ts.isBlock(node.statement)) {
96528                 writeSpace();
96529             }
96530             else {
96531                 writeLineOrSpace(node);
96532             }
96533             emitWhileClause(node, node.statement.end);
96534             writeTrailingSemicolon();
96535         }
96536         function emitWhileStatement(node) {
96537             emitWhileClause(node, node.pos);
96538             emitEmbeddedStatement(node, node.statement);
96539         }
96540         function emitForStatement(node) {
96541             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96542             writeSpace();
96543             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96544             emitForBinding(node.initializer);
96545             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96546             emitExpressionWithLeadingSpace(node.condition);
96547             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96548             emitExpressionWithLeadingSpace(node.incrementor);
96549             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96550             emitEmbeddedStatement(node, node.statement);
96551         }
96552         function emitForInStatement(node) {
96553             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96554             writeSpace();
96555             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96556             emitForBinding(node.initializer);
96557             writeSpace();
96558             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96559             writeSpace();
96560             emitExpression(node.expression);
96561             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96562             emitEmbeddedStatement(node, node.statement);
96563         }
96564         function emitForOfStatement(node) {
96565             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96566             writeSpace();
96567             emitWithTrailingSpace(node.awaitModifier);
96568             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96569             emitForBinding(node.initializer);
96570             writeSpace();
96571             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96572             writeSpace();
96573             emitExpression(node.expression);
96574             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96575             emitEmbeddedStatement(node, node.statement);
96576         }
96577         function emitForBinding(node) {
96578             if (node !== undefined) {
96579                 if (node.kind === 243 /* VariableDeclarationList */) {
96580                     emit(node);
96581                 }
96582                 else {
96583                     emitExpression(node);
96584                 }
96585             }
96586         }
96587         function emitContinueStatement(node) {
96588             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96589             emitWithLeadingSpace(node.label);
96590             writeTrailingSemicolon();
96591         }
96592         function emitBreakStatement(node) {
96593             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96594             emitWithLeadingSpace(node.label);
96595             writeTrailingSemicolon();
96596         }
96597         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96598             var node = ts.getParseTreeNode(contextNode);
96599             var isSimilarNode = node && node.kind === contextNode.kind;
96600             var startPos = pos;
96601             if (isSimilarNode && currentSourceFile) {
96602                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96603             }
96604             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96605                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96606                 if (needsIndent) {
96607                     increaseIndent();
96608                 }
96609                 emitLeadingCommentsOfPosition(startPos);
96610                 if (needsIndent) {
96611                     decreaseIndent();
96612                 }
96613             }
96614             pos = writeTokenText(token, writer, pos);
96615             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96616                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96617             }
96618             return pos;
96619         }
96620         function emitReturnStatement(node) {
96621             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96622             emitExpressionWithLeadingSpace(node.expression);
96623             writeTrailingSemicolon();
96624         }
96625         function emitWithStatement(node) {
96626             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96627             writeSpace();
96628             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96629             emitExpression(node.expression);
96630             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96631             emitEmbeddedStatement(node, node.statement);
96632         }
96633         function emitSwitchStatement(node) {
96634             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96635             writeSpace();
96636             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96637             emitExpression(node.expression);
96638             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96639             writeSpace();
96640             emit(node.caseBlock);
96641         }
96642         function emitLabeledStatement(node) {
96643             emit(node.label);
96644             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96645             writeSpace();
96646             emit(node.statement);
96647         }
96648         function emitThrowStatement(node) {
96649             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96650             emitExpressionWithLeadingSpace(node.expression);
96651             writeTrailingSemicolon();
96652         }
96653         function emitTryStatement(node) {
96654             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96655             writeSpace();
96656             emit(node.tryBlock);
96657             if (node.catchClause) {
96658                 writeLineOrSpace(node);
96659                 emit(node.catchClause);
96660             }
96661             if (node.finallyBlock) {
96662                 writeLineOrSpace(node);
96663                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96664                 writeSpace();
96665                 emit(node.finallyBlock);
96666             }
96667         }
96668         function emitDebuggerStatement(node) {
96669             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96670             writeTrailingSemicolon();
96671         }
96672         //
96673         // Declarations
96674         //
96675         function emitVariableDeclaration(node) {
96676             emit(node.name);
96677             emit(node.exclamationToken);
96678             emitTypeAnnotation(node.type);
96679             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96680         }
96681         function emitVariableDeclarationList(node) {
96682             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96683             writeSpace();
96684             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96685         }
96686         function emitFunctionDeclaration(node) {
96687             emitFunctionDeclarationOrExpression(node);
96688         }
96689         function emitFunctionDeclarationOrExpression(node) {
96690             emitDecorators(node, node.decorators);
96691             emitModifiers(node, node.modifiers);
96692             writeKeyword("function");
96693             emit(node.asteriskToken);
96694             writeSpace();
96695             emitIdentifierName(node.name);
96696             emitSignatureAndBody(node, emitSignatureHead);
96697         }
96698         function emitBlockCallback(_hint, body) {
96699             emitBlockFunctionBody(body);
96700         }
96701         function emitSignatureAndBody(node, emitSignatureHead) {
96702             var body = node.body;
96703             if (body) {
96704                 if (ts.isBlock(body)) {
96705                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96706                     if (indentedFlag) {
96707                         increaseIndent();
96708                     }
96709                     pushNameGenerationScope(node);
96710                     ts.forEach(node.parameters, generateNames);
96711                     generateNames(node.body);
96712                     emitSignatureHead(node);
96713                     if (onEmitNode) {
96714                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96715                     }
96716                     else {
96717                         emitBlockFunctionBody(body);
96718                     }
96719                     popNameGenerationScope(node);
96720                     if (indentedFlag) {
96721                         decreaseIndent();
96722                     }
96723                 }
96724                 else {
96725                     emitSignatureHead(node);
96726                     writeSpace();
96727                     emitExpression(body);
96728                 }
96729             }
96730             else {
96731                 emitSignatureHead(node);
96732                 writeTrailingSemicolon();
96733             }
96734         }
96735         function emitSignatureHead(node) {
96736             emitTypeParameters(node, node.typeParameters);
96737             emitParameters(node, node.parameters);
96738             emitTypeAnnotation(node.type);
96739         }
96740         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96741             // We must emit a function body as a single-line body in the following case:
96742             // * The body has NodeEmitFlags.SingleLine specified.
96743             // We must emit a function body as a multi-line body in the following cases:
96744             // * The body is explicitly marked as multi-line.
96745             // * A non-synthesized body's start and end position are on different lines.
96746             // * Any statement in the body starts on a new line.
96747             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96748                 return true;
96749             }
96750             if (body.multiLine) {
96751                 return false;
96752             }
96753             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96754                 return false;
96755             }
96756             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96757                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96758                 return false;
96759             }
96760             var previousStatement;
96761             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96762                 var statement = _b[_a];
96763                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96764                     return false;
96765                 }
96766                 previousStatement = statement;
96767             }
96768             return true;
96769         }
96770         function emitBlockFunctionBody(body) {
96771             writeSpace();
96772             writePunctuation("{");
96773             increaseIndent();
96774             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96775                 ? emitBlockFunctionBodyOnSingleLine
96776                 : emitBlockFunctionBodyWorker;
96777             if (emitBodyWithDetachedComments) {
96778                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96779             }
96780             else {
96781                 emitBlockFunctionBody(body);
96782             }
96783             decreaseIndent();
96784             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96785         }
96786         function emitBlockFunctionBodyOnSingleLine(body) {
96787             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96788         }
96789         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96790             // Emit all the prologue directives (like "use strict").
96791             var statementOffset = emitPrologueDirectives(body.statements);
96792             var pos = writer.getTextPos();
96793             emitHelpers(body);
96794             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96795                 decreaseIndent();
96796                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96797                 increaseIndent();
96798             }
96799             else {
96800                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96801             }
96802         }
96803         function emitClassDeclaration(node) {
96804             emitClassDeclarationOrExpression(node);
96805         }
96806         function emitClassDeclarationOrExpression(node) {
96807             ts.forEach(node.members, generateMemberNames);
96808             emitDecorators(node, node.decorators);
96809             emitModifiers(node, node.modifiers);
96810             writeKeyword("class");
96811             if (node.name) {
96812                 writeSpace();
96813                 emitIdentifierName(node.name);
96814             }
96815             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96816             if (indentedFlag) {
96817                 increaseIndent();
96818             }
96819             emitTypeParameters(node, node.typeParameters);
96820             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
96821             writeSpace();
96822             writePunctuation("{");
96823             emitList(node, node.members, 129 /* ClassMembers */);
96824             writePunctuation("}");
96825             if (indentedFlag) {
96826                 decreaseIndent();
96827             }
96828         }
96829         function emitInterfaceDeclaration(node) {
96830             emitDecorators(node, node.decorators);
96831             emitModifiers(node, node.modifiers);
96832             writeKeyword("interface");
96833             writeSpace();
96834             emit(node.name);
96835             emitTypeParameters(node, node.typeParameters);
96836             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
96837             writeSpace();
96838             writePunctuation("{");
96839             emitList(node, node.members, 129 /* InterfaceMembers */);
96840             writePunctuation("}");
96841         }
96842         function emitTypeAliasDeclaration(node) {
96843             emitDecorators(node, node.decorators);
96844             emitModifiers(node, node.modifiers);
96845             writeKeyword("type");
96846             writeSpace();
96847             emit(node.name);
96848             emitTypeParameters(node, node.typeParameters);
96849             writeSpace();
96850             writePunctuation("=");
96851             writeSpace();
96852             emit(node.type);
96853             writeTrailingSemicolon();
96854         }
96855         function emitEnumDeclaration(node) {
96856             emitModifiers(node, node.modifiers);
96857             writeKeyword("enum");
96858             writeSpace();
96859             emit(node.name);
96860             writeSpace();
96861             writePunctuation("{");
96862             emitList(node, node.members, 145 /* EnumMembers */);
96863             writePunctuation("}");
96864         }
96865         function emitModuleDeclaration(node) {
96866             emitModifiers(node, node.modifiers);
96867             if (~node.flags & 1024 /* GlobalAugmentation */) {
96868                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
96869                 writeSpace();
96870             }
96871             emit(node.name);
96872             var body = node.body;
96873             if (!body)
96874                 return writeTrailingSemicolon();
96875             while (body.kind === 249 /* ModuleDeclaration */) {
96876                 writePunctuation(".");
96877                 emit(body.name);
96878                 body = body.body;
96879             }
96880             writeSpace();
96881             emit(body);
96882         }
96883         function emitModuleBlock(node) {
96884             pushNameGenerationScope(node);
96885             ts.forEach(node.statements, generateNames);
96886             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
96887             popNameGenerationScope(node);
96888         }
96889         function emitCaseBlock(node) {
96890             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
96891             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
96892             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
96893         }
96894         function emitImportEqualsDeclaration(node) {
96895             emitModifiers(node, node.modifiers);
96896             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96897             writeSpace();
96898             emit(node.name);
96899             writeSpace();
96900             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
96901             writeSpace();
96902             emitModuleReference(node.moduleReference);
96903             writeTrailingSemicolon();
96904         }
96905         function emitModuleReference(node) {
96906             if (node.kind === 75 /* Identifier */) {
96907                 emitExpression(node);
96908             }
96909             else {
96910                 emit(node);
96911             }
96912         }
96913         function emitImportDeclaration(node) {
96914             emitModifiers(node, node.modifiers);
96915             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96916             writeSpace();
96917             if (node.importClause) {
96918                 emit(node.importClause);
96919                 writeSpace();
96920                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
96921                 writeSpace();
96922             }
96923             emitExpression(node.moduleSpecifier);
96924             writeTrailingSemicolon();
96925         }
96926         function emitImportClause(node) {
96927             if (node.isTypeOnly) {
96928                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
96929                 writeSpace();
96930             }
96931             emit(node.name);
96932             if (node.name && node.namedBindings) {
96933                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
96934                 writeSpace();
96935             }
96936             emit(node.namedBindings);
96937         }
96938         function emitNamespaceImport(node) {
96939             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96940             writeSpace();
96941             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
96942             writeSpace();
96943             emit(node.name);
96944         }
96945         function emitNamedImports(node) {
96946             emitNamedImportsOrExports(node);
96947         }
96948         function emitImportSpecifier(node) {
96949             emitImportOrExportSpecifier(node);
96950         }
96951         function emitExportAssignment(node) {
96952             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96953             writeSpace();
96954             if (node.isExportEquals) {
96955                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
96956             }
96957             else {
96958                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
96959             }
96960             writeSpace();
96961             emitExpression(node.expression);
96962             writeTrailingSemicolon();
96963         }
96964         function emitExportDeclaration(node) {
96965             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96966             writeSpace();
96967             if (node.isTypeOnly) {
96968                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
96969                 writeSpace();
96970             }
96971             if (node.exportClause) {
96972                 emit(node.exportClause);
96973             }
96974             else {
96975                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
96976             }
96977             if (node.moduleSpecifier) {
96978                 writeSpace();
96979                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
96980                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
96981                 writeSpace();
96982                 emitExpression(node.moduleSpecifier);
96983             }
96984             writeTrailingSemicolon();
96985         }
96986         function emitNamespaceExportDeclaration(node) {
96987             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96988             writeSpace();
96989             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
96990             writeSpace();
96991             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
96992             writeSpace();
96993             emit(node.name);
96994             writeTrailingSemicolon();
96995         }
96996         function emitNamespaceExport(node) {
96997             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96998             writeSpace();
96999             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97000             writeSpace();
97001             emit(node.name);
97002         }
97003         function emitNamedExports(node) {
97004             emitNamedImportsOrExports(node);
97005         }
97006         function emitExportSpecifier(node) {
97007             emitImportOrExportSpecifier(node);
97008         }
97009         function emitNamedImportsOrExports(node) {
97010             writePunctuation("{");
97011             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97012             writePunctuation("}");
97013         }
97014         function emitImportOrExportSpecifier(node) {
97015             if (node.propertyName) {
97016                 emit(node.propertyName);
97017                 writeSpace();
97018                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97019                 writeSpace();
97020             }
97021             emit(node.name);
97022         }
97023         //
97024         // Module references
97025         //
97026         function emitExternalModuleReference(node) {
97027             writeKeyword("require");
97028             writePunctuation("(");
97029             emitExpression(node.expression);
97030             writePunctuation(")");
97031         }
97032         //
97033         // JSX
97034         //
97035         function emitJsxElement(node) {
97036             emit(node.openingElement);
97037             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97038             emit(node.closingElement);
97039         }
97040         function emitJsxSelfClosingElement(node) {
97041             writePunctuation("<");
97042             emitJsxTagName(node.tagName);
97043             emitTypeArguments(node, node.typeArguments);
97044             writeSpace();
97045             emit(node.attributes);
97046             writePunctuation("/>");
97047         }
97048         function emitJsxFragment(node) {
97049             emit(node.openingFragment);
97050             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97051             emit(node.closingFragment);
97052         }
97053         function emitJsxOpeningElementOrFragment(node) {
97054             writePunctuation("<");
97055             if (ts.isJsxOpeningElement(node)) {
97056                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97057                 emitJsxTagName(node.tagName);
97058                 emitTypeArguments(node, node.typeArguments);
97059                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97060                     writeSpace();
97061                 }
97062                 emit(node.attributes);
97063                 writeLineSeparatorsAfter(node.attributes, node);
97064                 decreaseIndentIf(indented);
97065             }
97066             writePunctuation(">");
97067         }
97068         function emitJsxText(node) {
97069             writer.writeLiteral(node.text);
97070         }
97071         function emitJsxClosingElementOrFragment(node) {
97072             writePunctuation("</");
97073             if (ts.isJsxClosingElement(node)) {
97074                 emitJsxTagName(node.tagName);
97075             }
97076             writePunctuation(">");
97077         }
97078         function emitJsxAttributes(node) {
97079             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97080         }
97081         function emitJsxAttribute(node) {
97082             emit(node.name);
97083             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97084         }
97085         function emitJsxSpreadAttribute(node) {
97086             writePunctuation("{...");
97087             emitExpression(node.expression);
97088             writePunctuation("}");
97089         }
97090         function emitJsxExpression(node) {
97091             if (node.expression) {
97092                 writePunctuation("{");
97093                 emit(node.dotDotDotToken);
97094                 emitExpression(node.expression);
97095                 writePunctuation("}");
97096             }
97097         }
97098         function emitJsxTagName(node) {
97099             if (node.kind === 75 /* Identifier */) {
97100                 emitExpression(node);
97101             }
97102             else {
97103                 emit(node);
97104             }
97105         }
97106         //
97107         // Clauses
97108         //
97109         function emitCaseClause(node) {
97110             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97111             writeSpace();
97112             emitExpression(node.expression);
97113             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97114         }
97115         function emitDefaultClause(node) {
97116             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97117             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97118         }
97119         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97120             var emitAsSingleStatement = statements.length === 1 &&
97121                 (
97122                 // treat synthesized nodes as located on the same line for emit purposes
97123                 ts.nodeIsSynthesized(parentNode) ||
97124                     ts.nodeIsSynthesized(statements[0]) ||
97125                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97126             var format = 163969 /* CaseOrDefaultClauseStatements */;
97127             if (emitAsSingleStatement) {
97128                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97129                 writeSpace();
97130                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97131             }
97132             else {
97133                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97134             }
97135             emitList(parentNode, statements, format);
97136         }
97137         function emitHeritageClause(node) {
97138             writeSpace();
97139             writeTokenText(node.token, writeKeyword);
97140             writeSpace();
97141             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97142         }
97143         function emitCatchClause(node) {
97144             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97145             writeSpace();
97146             if (node.variableDeclaration) {
97147                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97148                 emit(node.variableDeclaration);
97149                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97150                 writeSpace();
97151             }
97152             emit(node.block);
97153         }
97154         //
97155         // Property assignments
97156         //
97157         function emitPropertyAssignment(node) {
97158             emit(node.name);
97159             writePunctuation(":");
97160             writeSpace();
97161             // This is to ensure that we emit comment in the following case:
97162             //      For example:
97163             //          obj = {
97164             //              id: /*comment1*/ ()=>void
97165             //          }
97166             // "comment1" is not considered to be leading comment for node.initializer
97167             // but rather a trailing comment on the previous node.
97168             var initializer = node.initializer;
97169             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97170                 var commentRange = ts.getCommentRange(initializer);
97171                 emitTrailingCommentsOfPosition(commentRange.pos);
97172             }
97173             emitExpression(initializer);
97174         }
97175         function emitShorthandPropertyAssignment(node) {
97176             emit(node.name);
97177             if (node.objectAssignmentInitializer) {
97178                 writeSpace();
97179                 writePunctuation("=");
97180                 writeSpace();
97181                 emitExpression(node.objectAssignmentInitializer);
97182             }
97183         }
97184         function emitSpreadAssignment(node) {
97185             if (node.expression) {
97186                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97187                 emitExpression(node.expression);
97188             }
97189         }
97190         //
97191         // Enum
97192         //
97193         function emitEnumMember(node) {
97194             emit(node.name);
97195             emitInitializer(node.initializer, node.name.end, node);
97196         }
97197         //
97198         // JSDoc
97199         //
97200         function emitJSDoc(node) {
97201             write("/**");
97202             if (node.comment) {
97203                 var lines = node.comment.split(/\r\n?|\n/g);
97204                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97205                     var line = lines_2[_a];
97206                     writeLine();
97207                     writeSpace();
97208                     writePunctuation("*");
97209                     writeSpace();
97210                     write(line);
97211                 }
97212             }
97213             if (node.tags) {
97214                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97215                     writeSpace();
97216                     emit(node.tags[0]);
97217                 }
97218                 else {
97219                     emitList(node, node.tags, 33 /* JSDocComment */);
97220                 }
97221             }
97222             writeSpace();
97223             write("*/");
97224         }
97225         function emitJSDocSimpleTypedTag(tag) {
97226             emitJSDocTagName(tag.tagName);
97227             emitJSDocTypeExpression(tag.typeExpression);
97228             emitJSDocComment(tag.comment);
97229         }
97230         function emitJSDocHeritageTag(tag) {
97231             emitJSDocTagName(tag.tagName);
97232             writeSpace();
97233             writePunctuation("{");
97234             emit(tag.class);
97235             writePunctuation("}");
97236             emitJSDocComment(tag.comment);
97237         }
97238         function emitJSDocTemplateTag(tag) {
97239             emitJSDocTagName(tag.tagName);
97240             emitJSDocTypeExpression(tag.constraint);
97241             writeSpace();
97242             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97243             emitJSDocComment(tag.comment);
97244         }
97245         function emitJSDocTypedefTag(tag) {
97246             emitJSDocTagName(tag.tagName);
97247             if (tag.typeExpression) {
97248                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97249                     emitJSDocTypeExpression(tag.typeExpression);
97250                 }
97251                 else {
97252                     writeSpace();
97253                     writePunctuation("{");
97254                     write("Object");
97255                     if (tag.typeExpression.isArrayType) {
97256                         writePunctuation("[");
97257                         writePunctuation("]");
97258                     }
97259                     writePunctuation("}");
97260                 }
97261             }
97262             if (tag.fullName) {
97263                 writeSpace();
97264                 emit(tag.fullName);
97265             }
97266             emitJSDocComment(tag.comment);
97267             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97268                 emitJSDocTypeLiteral(tag.typeExpression);
97269             }
97270         }
97271         function emitJSDocCallbackTag(tag) {
97272             emitJSDocTagName(tag.tagName);
97273             if (tag.name) {
97274                 writeSpace();
97275                 emit(tag.name);
97276             }
97277             emitJSDocComment(tag.comment);
97278             emitJSDocSignature(tag.typeExpression);
97279         }
97280         function emitJSDocSimpleTag(tag) {
97281             emitJSDocTagName(tag.tagName);
97282             emitJSDocComment(tag.comment);
97283         }
97284         function emitJSDocTypeLiteral(lit) {
97285             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97286         }
97287         function emitJSDocSignature(sig) {
97288             if (sig.typeParameters) {
97289                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97290             }
97291             if (sig.parameters) {
97292                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97293             }
97294             if (sig.type) {
97295                 writeLine();
97296                 writeSpace();
97297                 writePunctuation("*");
97298                 writeSpace();
97299                 emit(sig.type);
97300             }
97301         }
97302         function emitJSDocPropertyLikeTag(param) {
97303             emitJSDocTagName(param.tagName);
97304             emitJSDocTypeExpression(param.typeExpression);
97305             writeSpace();
97306             if (param.isBracketed) {
97307                 writePunctuation("[");
97308             }
97309             emit(param.name);
97310             if (param.isBracketed) {
97311                 writePunctuation("]");
97312             }
97313             emitJSDocComment(param.comment);
97314         }
97315         function emitJSDocTagName(tagName) {
97316             writePunctuation("@");
97317             emit(tagName);
97318         }
97319         function emitJSDocComment(comment) {
97320             if (comment) {
97321                 writeSpace();
97322                 write(comment);
97323             }
97324         }
97325         function emitJSDocTypeExpression(typeExpression) {
97326             if (typeExpression) {
97327                 writeSpace();
97328                 writePunctuation("{");
97329                 emit(typeExpression.type);
97330                 writePunctuation("}");
97331             }
97332         }
97333         //
97334         // Top-level nodes
97335         //
97336         function emitSourceFile(node) {
97337             writeLine();
97338             var statements = node.statements;
97339             if (emitBodyWithDetachedComments) {
97340                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97341                 // The synthesized node will have no leading comment so some comments may be missed.
97342                 var shouldEmitDetachedComment = statements.length === 0 ||
97343                     !ts.isPrologueDirective(statements[0]) ||
97344                     ts.nodeIsSynthesized(statements[0]);
97345                 if (shouldEmitDetachedComment) {
97346                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97347                     return;
97348                 }
97349             }
97350             emitSourceFileWorker(node);
97351         }
97352         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97353             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97354             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97355                 var prepend = _b[_a];
97356                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97357                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97358                         var ref = _d[_c];
97359                         emit(ref);
97360                         writeLine();
97361                     }
97362                 }
97363             }
97364         }
97365         function emitTripleSlashDirectivesIfNeeded(node) {
97366             if (node.isDeclarationFile)
97367                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97368         }
97369         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97370             if (hasNoDefaultLib) {
97371                 var pos = writer.getTextPos();
97372                 writeComment("/// <reference no-default-lib=\"true\"/>");
97373                 if (bundleFileInfo)
97374                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97375                 writeLine();
97376             }
97377             if (currentSourceFile && currentSourceFile.moduleName) {
97378                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97379                 writeLine();
97380             }
97381             if (currentSourceFile && currentSourceFile.amdDependencies) {
97382                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97383                     var dep = _b[_a];
97384                     if (dep.name) {
97385                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97386                     }
97387                     else {
97388                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97389                     }
97390                     writeLine();
97391                 }
97392             }
97393             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97394                 var directive = files_1[_c];
97395                 var pos = writer.getTextPos();
97396                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97397                 if (bundleFileInfo)
97398                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97399                 writeLine();
97400             }
97401             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97402                 var directive = types_22[_d];
97403                 var pos = writer.getTextPos();
97404                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97405                 if (bundleFileInfo)
97406                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97407                 writeLine();
97408             }
97409             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97410                 var directive = libs_1[_e];
97411                 var pos = writer.getTextPos();
97412                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97413                 if (bundleFileInfo)
97414                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97415                 writeLine();
97416             }
97417         }
97418         function emitSourceFileWorker(node) {
97419             var statements = node.statements;
97420             pushNameGenerationScope(node);
97421             ts.forEach(node.statements, generateNames);
97422             emitHelpers(node);
97423             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97424             emitTripleSlashDirectivesIfNeeded(node);
97425             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97426             popNameGenerationScope(node);
97427         }
97428         // Transformation nodes
97429         function emitPartiallyEmittedExpression(node) {
97430             emitExpression(node.expression);
97431         }
97432         function emitCommaList(node) {
97433             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97434         }
97435         /**
97436          * Emits any prologue directives at the start of a Statement list, returning the
97437          * number of prologue directives written to the output.
97438          */
97439         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97440             var needsToSetSourceFile = !!sourceFile;
97441             for (var i = 0; i < statements.length; i++) {
97442                 var statement = statements[i];
97443                 if (ts.isPrologueDirective(statement)) {
97444                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97445                     if (shouldEmitPrologueDirective) {
97446                         if (needsToSetSourceFile) {
97447                             needsToSetSourceFile = false;
97448                             setSourceFile(sourceFile);
97449                         }
97450                         writeLine();
97451                         var pos = writer.getTextPos();
97452                         emit(statement);
97453                         if (recordBundleFileSection && bundleFileInfo)
97454                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97455                         if (seenPrologueDirectives) {
97456                             seenPrologueDirectives.set(statement.expression.text, true);
97457                         }
97458                     }
97459                 }
97460                 else {
97461                     // return index of the first non prologue directive
97462                     return i;
97463                 }
97464             }
97465             return statements.length;
97466         }
97467         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97468             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97469                 var prologue = prologues_1[_a];
97470                 if (!seenPrologueDirectives.has(prologue.data)) {
97471                     writeLine();
97472                     var pos = writer.getTextPos();
97473                     emit(prologue);
97474                     if (bundleFileInfo)
97475                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97476                     if (seenPrologueDirectives) {
97477                         seenPrologueDirectives.set(prologue.data, true);
97478                     }
97479                 }
97480             }
97481         }
97482         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97483             if (ts.isSourceFile(sourceFileOrBundle)) {
97484                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97485             }
97486             else {
97487                 var seenPrologueDirectives = ts.createMap();
97488                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97489                     var prepend = _b[_a];
97490                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97491                 }
97492                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97493                     var sourceFile = _d[_c];
97494                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97495                 }
97496                 setSourceFile(undefined);
97497             }
97498         }
97499         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97500             var seenPrologueDirectives = ts.createMap();
97501             var prologues;
97502             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97503                 var sourceFile = bundle.sourceFiles[index];
97504                 var directives = void 0;
97505                 var end = 0;
97506                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97507                     var statement = _b[_a];
97508                     if (!ts.isPrologueDirective(statement))
97509                         break;
97510                     if (seenPrologueDirectives.has(statement.expression.text))
97511                         continue;
97512                     seenPrologueDirectives.set(statement.expression.text, true);
97513                     (directives || (directives = [])).push({
97514                         pos: statement.pos,
97515                         end: statement.end,
97516                         expression: {
97517                             pos: statement.expression.pos,
97518                             end: statement.expression.end,
97519                             text: statement.expression.text
97520                         }
97521                     });
97522                     end = end < statement.end ? statement.end : end;
97523                 }
97524                 if (directives)
97525                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97526             }
97527             return prologues;
97528         }
97529         function emitShebangIfNeeded(sourceFileOrBundle) {
97530             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97531                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97532                 if (shebang) {
97533                     writeComment(shebang);
97534                     writeLine();
97535                     return true;
97536                 }
97537             }
97538             else {
97539                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97540                     var prepend = _b[_a];
97541                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97542                     if (emitShebangIfNeeded(prepend)) {
97543                         return true;
97544                     }
97545                 }
97546                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97547                     var sourceFile = _d[_c];
97548                     // Emit only the first encountered shebang
97549                     if (emitShebangIfNeeded(sourceFile)) {
97550                         return true;
97551                     }
97552                 }
97553             }
97554         }
97555         //
97556         // Helpers
97557         //
97558         function emitNodeWithWriter(node, writer) {
97559             if (!node)
97560                 return;
97561             var savedWrite = write;
97562             write = writer;
97563             emit(node);
97564             write = savedWrite;
97565         }
97566         function emitModifiers(node, modifiers) {
97567             if (modifiers && modifiers.length) {
97568                 emitList(node, modifiers, 262656 /* Modifiers */);
97569                 writeSpace();
97570             }
97571         }
97572         function emitTypeAnnotation(node) {
97573             if (node) {
97574                 writePunctuation(":");
97575                 writeSpace();
97576                 emit(node);
97577             }
97578         }
97579         function emitInitializer(node, equalCommentStartPos, container) {
97580             if (node) {
97581                 writeSpace();
97582                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97583                 writeSpace();
97584                 emitExpression(node);
97585             }
97586         }
97587         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97588             if (node) {
97589                 prefixWriter(prefix);
97590                 emit(node);
97591             }
97592         }
97593         function emitWithLeadingSpace(node) {
97594             if (node) {
97595                 writeSpace();
97596                 emit(node);
97597             }
97598         }
97599         function emitExpressionWithLeadingSpace(node) {
97600             if (node) {
97601                 writeSpace();
97602                 emitExpression(node);
97603             }
97604         }
97605         function emitWithTrailingSpace(node) {
97606             if (node) {
97607                 emit(node);
97608                 writeSpace();
97609             }
97610         }
97611         function emitEmbeddedStatement(parent, node) {
97612             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97613                 writeSpace();
97614                 emit(node);
97615             }
97616             else {
97617                 writeLine();
97618                 increaseIndent();
97619                 if (ts.isEmptyStatement(node)) {
97620                     pipelineEmit(5 /* EmbeddedStatement */, node);
97621                 }
97622                 else {
97623                     emit(node);
97624                 }
97625                 decreaseIndent();
97626             }
97627         }
97628         function emitDecorators(parentNode, decorators) {
97629             emitList(parentNode, decorators, 2146305 /* Decorators */);
97630         }
97631         function emitTypeArguments(parentNode, typeArguments) {
97632             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97633         }
97634         function emitTypeParameters(parentNode, typeParameters) {
97635             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97636                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97637             }
97638             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97639         }
97640         function emitParameters(parentNode, parameters) {
97641             emitList(parentNode, parameters, 2576 /* Parameters */);
97642         }
97643         function canEmitSimpleArrowHead(parentNode, parameters) {
97644             var parameter = ts.singleOrUndefined(parameters);
97645             return parameter
97646                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97647                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97648                 && !parentNode.type // arrow function may not have return type annotation
97649                 && !ts.some(parentNode.decorators) // parent may not have decorators
97650                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97651                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97652                 && !ts.some(parameter.decorators) // parameter may not have decorators
97653                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97654                 && !parameter.dotDotDotToken // parameter may not be rest
97655                 && !parameter.questionToken // parameter may not be optional
97656                 && !parameter.type // parameter may not have a type annotation
97657                 && !parameter.initializer // parameter may not have an initializer
97658                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97659         }
97660         function emitParametersForArrow(parentNode, parameters) {
97661             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97662                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97663             }
97664             else {
97665                 emitParameters(parentNode, parameters);
97666             }
97667         }
97668         function emitParametersForIndexSignature(parentNode, parameters) {
97669             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97670         }
97671         function emitList(parentNode, children, format, start, count) {
97672             emitNodeList(emit, parentNode, children, format, start, count);
97673         }
97674         function emitExpressionList(parentNode, children, format, start, count) {
97675             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97676         }
97677         function writeDelimiter(format) {
97678             switch (format & 60 /* DelimitersMask */) {
97679                 case 0 /* None */:
97680                     break;
97681                 case 16 /* CommaDelimited */:
97682                     writePunctuation(",");
97683                     break;
97684                 case 4 /* BarDelimited */:
97685                     writeSpace();
97686                     writePunctuation("|");
97687                     break;
97688                 case 32 /* AsteriskDelimited */:
97689                     writeSpace();
97690                     writePunctuation("*");
97691                     writeSpace();
97692                     break;
97693                 case 8 /* AmpersandDelimited */:
97694                     writeSpace();
97695                     writePunctuation("&");
97696                     break;
97697             }
97698         }
97699         function emitNodeList(emit, parentNode, children, format, start, count) {
97700             if (start === void 0) { start = 0; }
97701             if (count === void 0) { count = children ? children.length - start : 0; }
97702             var isUndefined = children === undefined;
97703             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97704                 return;
97705             }
97706             var isEmpty = children === undefined || start >= children.length || count === 0;
97707             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97708                 if (onBeforeEmitNodeArray) {
97709                     onBeforeEmitNodeArray(children);
97710                 }
97711                 if (onAfterEmitNodeArray) {
97712                     onAfterEmitNodeArray(children);
97713                 }
97714                 return;
97715             }
97716             if (format & 15360 /* BracketsMask */) {
97717                 writePunctuation(getOpeningBracket(format));
97718                 if (isEmpty && !isUndefined) {
97719                     // TODO: GH#18217
97720                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97721                 }
97722             }
97723             if (onBeforeEmitNodeArray) {
97724                 onBeforeEmitNodeArray(children);
97725             }
97726             if (isEmpty) {
97727                 // Write a line terminator if the parent node was multi-line
97728                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97729                     writeLine();
97730                 }
97731                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97732                     writeSpace();
97733                 }
97734             }
97735             else {
97736                 // Write the opening line terminator or leading whitespace.
97737                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97738                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97739                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97740                 if (leadingLineTerminatorCount) {
97741                     writeLine(leadingLineTerminatorCount);
97742                     shouldEmitInterveningComments = false;
97743                 }
97744                 else if (format & 256 /* SpaceBetweenBraces */) {
97745                     writeSpace();
97746                 }
97747                 // Increase the indent, if requested.
97748                 if (format & 128 /* Indented */) {
97749                     increaseIndent();
97750                 }
97751                 // Emit each child.
97752                 var previousSibling = void 0;
97753                 var previousSourceFileTextKind = void 0;
97754                 var shouldDecreaseIndentAfterEmit = false;
97755                 for (var i = 0; i < count; i++) {
97756                     var child = children[start + i];
97757                     // Write the delimiter if this is not the first node.
97758                     if (format & 32 /* AsteriskDelimited */) {
97759                         // always write JSDoc in the format "\n *"
97760                         writeLine();
97761                         writeDelimiter(format);
97762                     }
97763                     else if (previousSibling) {
97764                         // i.e
97765                         //      function commentedParameters(
97766                         //          /* Parameter a */
97767                         //          a
97768                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97769                         //          ,
97770                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97771                             emitLeadingCommentsOfPosition(previousSibling.end);
97772                         }
97773                         writeDelimiter(format);
97774                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97775                         // Write either a line terminator or whitespace to separate the elements.
97776                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97777                         if (separatingLineTerminatorCount > 0) {
97778                             // If a synthesized node in a single-line list starts on a new
97779                             // line, we should increase the indent.
97780                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97781                                 increaseIndent();
97782                                 shouldDecreaseIndentAfterEmit = true;
97783                             }
97784                             writeLine(separatingLineTerminatorCount);
97785                             shouldEmitInterveningComments = false;
97786                         }
97787                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97788                             writeSpace();
97789                         }
97790                     }
97791                     // Emit this child.
97792                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97793                     if (shouldEmitInterveningComments) {
97794                         if (emitTrailingCommentsOfPosition) {
97795                             var commentRange = ts.getCommentRange(child);
97796                             emitTrailingCommentsOfPosition(commentRange.pos);
97797                         }
97798                     }
97799                     else {
97800                         shouldEmitInterveningComments = mayEmitInterveningComments;
97801                     }
97802                     emit(child);
97803                     if (shouldDecreaseIndentAfterEmit) {
97804                         decreaseIndent();
97805                         shouldDecreaseIndentAfterEmit = false;
97806                     }
97807                     previousSibling = child;
97808                 }
97809                 // Write a trailing comma, if requested.
97810                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97811                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
97812                     writePunctuation(",");
97813                 }
97814                 // Emit any trailing comment of the last element in the list
97815                 // i.e
97816                 //       var array = [...
97817                 //          2
97818                 //          /* end of element 2 */
97819                 //       ];
97820                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
97821                     emitLeadingCommentsOfPosition(previousSibling.end);
97822                 }
97823                 // Decrease the indent, if requested.
97824                 if (format & 128 /* Indented */) {
97825                     decreaseIndent();
97826                 }
97827                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97828                 // Write the closing line terminator or closing whitespace.
97829                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
97830                 if (closingLineTerminatorCount) {
97831                     writeLine(closingLineTerminatorCount);
97832                 }
97833                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
97834                     writeSpace();
97835                 }
97836             }
97837             if (onAfterEmitNodeArray) {
97838                 onAfterEmitNodeArray(children);
97839             }
97840             if (format & 15360 /* BracketsMask */) {
97841                 if (isEmpty && !isUndefined) {
97842                     // TODO: GH#18217
97843                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
97844                 }
97845                 writePunctuation(getClosingBracket(format));
97846             }
97847         }
97848         // Writers
97849         function writeLiteral(s) {
97850             writer.writeLiteral(s);
97851         }
97852         function writeStringLiteral(s) {
97853             writer.writeStringLiteral(s);
97854         }
97855         function writeBase(s) {
97856             writer.write(s);
97857         }
97858         function writeSymbol(s, sym) {
97859             writer.writeSymbol(s, sym);
97860         }
97861         function writePunctuation(s) {
97862             writer.writePunctuation(s);
97863         }
97864         function writeTrailingSemicolon() {
97865             writer.writeTrailingSemicolon(";");
97866         }
97867         function writeKeyword(s) {
97868             writer.writeKeyword(s);
97869         }
97870         function writeOperator(s) {
97871             writer.writeOperator(s);
97872         }
97873         function writeParameter(s) {
97874             writer.writeParameter(s);
97875         }
97876         function writeComment(s) {
97877             writer.writeComment(s);
97878         }
97879         function writeSpace() {
97880             writer.writeSpace(" ");
97881         }
97882         function writeProperty(s) {
97883             writer.writeProperty(s);
97884         }
97885         function writeLine(count) {
97886             if (count === void 0) { count = 1; }
97887             for (var i = 0; i < count; i++) {
97888                 writer.writeLine(i > 0);
97889             }
97890         }
97891         function increaseIndent() {
97892             writer.increaseIndent();
97893         }
97894         function decreaseIndent() {
97895             writer.decreaseIndent();
97896         }
97897         function writeToken(token, pos, writer, contextNode) {
97898             return !sourceMapsDisabled
97899                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
97900                 : writeTokenText(token, writer, pos);
97901         }
97902         function writeTokenNode(node, writer) {
97903             if (onBeforeEmitToken) {
97904                 onBeforeEmitToken(node);
97905             }
97906             writer(ts.tokenToString(node.kind));
97907             if (onAfterEmitToken) {
97908                 onAfterEmitToken(node);
97909             }
97910         }
97911         function writeTokenText(token, writer, pos) {
97912             var tokenString = ts.tokenToString(token);
97913             writer(tokenString);
97914             return pos < 0 ? pos : pos + tokenString.length;
97915         }
97916         function writeLineOrSpace(node) {
97917             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
97918                 writeSpace();
97919             }
97920             else {
97921                 writeLine();
97922             }
97923         }
97924         function writeLines(text) {
97925             var lines = text.split(/\r\n?|\n/g);
97926             var indentation = ts.guessIndentation(lines);
97927             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
97928                 var lineText = lines_3[_a];
97929                 var line = indentation ? lineText.slice(indentation) : lineText;
97930                 if (line.length) {
97931                     writeLine();
97932                     write(line);
97933                 }
97934             }
97935         }
97936         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
97937             if (lineCount) {
97938                 increaseIndent();
97939                 writeLine(lineCount);
97940             }
97941             else if (writeSpaceIfNotIndenting) {
97942                 writeSpace();
97943             }
97944         }
97945         // Helper function to decrease the indent if we previously indented.  Allows multiple
97946         // previous indent values to be considered at a time.  This also allows caller to just
97947         // call this once, passing in all their appropriate indent values, instead of needing
97948         // to call this helper function multiple times.
97949         function decreaseIndentIf(value1, value2) {
97950             if (value1) {
97951                 decreaseIndent();
97952             }
97953             if (value2) {
97954                 decreaseIndent();
97955             }
97956         }
97957         function getLeadingLineTerminatorCount(parentNode, children, format) {
97958             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
97959                 if (format & 65536 /* PreferNewLine */) {
97960                     return 1;
97961                 }
97962                 var firstChild_1 = children[0];
97963                 if (firstChild_1 === undefined) {
97964                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
97965                 }
97966                 if (firstChild_1.kind === 11 /* JsxText */) {
97967                     // JsxText will be written with its leading whitespace, so don't add more manually.
97968                     return 0;
97969                 }
97970                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
97971                     if (preserveSourceNewlines) {
97972                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
97973                     }
97974                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
97975                 }
97976                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
97977                     return 1;
97978                 }
97979             }
97980             return format & 1 /* MultiLine */ ? 1 : 0;
97981         }
97982         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
97983             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
97984                 if (previousNode === undefined || nextNode === undefined) {
97985                     return 0;
97986                 }
97987                 if (nextNode.kind === 11 /* JsxText */) {
97988                     // JsxText will be written with its leading whitespace, so don't add more manually.
97989                     return 0;
97990                 }
97991                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
97992                     if (preserveSourceNewlines) {
97993                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
97994                     }
97995                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
97996                 }
97997                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
97998                     return 1;
97999                 }
98000             }
98001             else if (ts.getStartsOnNewLine(nextNode)) {
98002                 return 1;
98003             }
98004             return format & 1 /* MultiLine */ ? 1 : 0;
98005         }
98006         function getClosingLineTerminatorCount(parentNode, children, format) {
98007             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98008                 if (format & 65536 /* PreferNewLine */) {
98009                     return 1;
98010                 }
98011                 var lastChild_1 = ts.lastOrUndefined(children);
98012                 if (lastChild_1 === undefined) {
98013                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98014                 }
98015                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98016                     if (preserveSourceNewlines) {
98017                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98018                     }
98019                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98020                 }
98021                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98022                     return 1;
98023                 }
98024             }
98025             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98026                 return 1;
98027             }
98028             return 0;
98029         }
98030         function getEffectiveLines(getLineDifference) {
98031             // If 'preserveSourceNewlines' is disabled, we should never call this function
98032             // because it could be more expensive than alternative approximations.
98033             ts.Debug.assert(!!preserveSourceNewlines);
98034             // We start by measuring the line difference from a position to its adjacent comments,
98035             // so that this is counted as a one-line difference, not two:
98036             //
98037             //   node1;
98038             //   // NODE2 COMMENT
98039             //   node2;
98040             var lines = getLineDifference(/*includeComments*/ true);
98041             if (lines === 0) {
98042                 // However, if the line difference considering comments was 0, we might have this:
98043                 //
98044                 //   node1; // NODE2 COMMENT
98045                 //   node2;
98046                 //
98047                 // in which case we should be ignoring node2's comment, so this too is counted as
98048                 // a one-line difference, not zero.
98049                 return getLineDifference(/*includeComments*/ false);
98050             }
98051             return lines;
98052         }
98053         function writeLineSeparatorsAndIndentBefore(node, parent) {
98054             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98055             if (leadingNewlines) {
98056                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98057             }
98058             return !!leadingNewlines;
98059         }
98060         function writeLineSeparatorsAfter(node, parent) {
98061             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98062             if (trailingNewlines) {
98063                 writeLine(trailingNewlines);
98064             }
98065         }
98066         function synthesizedNodeStartsOnNewLine(node, format) {
98067             if (ts.nodeIsSynthesized(node)) {
98068                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98069                 if (startsOnNewLine === undefined) {
98070                     return (format & 65536 /* PreferNewLine */) !== 0;
98071                 }
98072                 return startsOnNewLine;
98073             }
98074             return (format & 65536 /* PreferNewLine */) !== 0;
98075         }
98076         function getLinesBetweenNodes(parent, node1, node2) {
98077             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98078                 return 0;
98079             }
98080             parent = skipSynthesizedParentheses(parent);
98081             node1 = skipSynthesizedParentheses(node1);
98082             node2 = skipSynthesizedParentheses(node2);
98083             // Always use a newline for synthesized code if the synthesizer desires it.
98084             if (ts.getStartsOnNewLine(node2)) {
98085                 return 1;
98086             }
98087             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98088                 if (preserveSourceNewlines) {
98089                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98090                 }
98091                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98092             }
98093             return 0;
98094         }
98095         function isEmptyBlock(block) {
98096             return block.statements.length === 0
98097                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98098         }
98099         function skipSynthesizedParentheses(node) {
98100             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98101                 node = node.expression;
98102             }
98103             return node;
98104         }
98105         function getTextOfNode(node, includeTrivia) {
98106             if (ts.isGeneratedIdentifier(node)) {
98107                 return generateName(node);
98108             }
98109             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98110                 return ts.idText(node);
98111             }
98112             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98113                 return getTextOfNode(node.textSourceNode, includeTrivia);
98114             }
98115             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98116                 return node.text;
98117             }
98118             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98119         }
98120         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98121             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98122                 var textSourceNode = node.textSourceNode;
98123                 if (ts.isIdentifier(textSourceNode)) {
98124                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98125                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98126                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98127                 }
98128                 else {
98129                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98130                 }
98131             }
98132             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98133         }
98134         /**
98135          * Push a new name generation scope.
98136          */
98137         function pushNameGenerationScope(node) {
98138             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98139                 return;
98140             }
98141             tempFlagsStack.push(tempFlags);
98142             tempFlags = 0;
98143             reservedNamesStack.push(reservedNames);
98144         }
98145         /**
98146          * Pop the current name generation scope.
98147          */
98148         function popNameGenerationScope(node) {
98149             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98150                 return;
98151             }
98152             tempFlags = tempFlagsStack.pop();
98153             reservedNames = reservedNamesStack.pop();
98154         }
98155         function reserveNameInNestedScopes(name) {
98156             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98157                 reservedNames = ts.createMap();
98158             }
98159             reservedNames.set(name, true);
98160         }
98161         function generateNames(node) {
98162             if (!node)
98163                 return;
98164             switch (node.kind) {
98165                 case 223 /* Block */:
98166                     ts.forEach(node.statements, generateNames);
98167                     break;
98168                 case 238 /* LabeledStatement */:
98169                 case 236 /* WithStatement */:
98170                 case 228 /* DoStatement */:
98171                 case 229 /* WhileStatement */:
98172                     generateNames(node.statement);
98173                     break;
98174                 case 227 /* IfStatement */:
98175                     generateNames(node.thenStatement);
98176                     generateNames(node.elseStatement);
98177                     break;
98178                 case 230 /* ForStatement */:
98179                 case 232 /* ForOfStatement */:
98180                 case 231 /* ForInStatement */:
98181                     generateNames(node.initializer);
98182                     generateNames(node.statement);
98183                     break;
98184                 case 237 /* SwitchStatement */:
98185                     generateNames(node.caseBlock);
98186                     break;
98187                 case 251 /* CaseBlock */:
98188                     ts.forEach(node.clauses, generateNames);
98189                     break;
98190                 case 277 /* CaseClause */:
98191                 case 278 /* DefaultClause */:
98192                     ts.forEach(node.statements, generateNames);
98193                     break;
98194                 case 240 /* TryStatement */:
98195                     generateNames(node.tryBlock);
98196                     generateNames(node.catchClause);
98197                     generateNames(node.finallyBlock);
98198                     break;
98199                 case 280 /* CatchClause */:
98200                     generateNames(node.variableDeclaration);
98201                     generateNames(node.block);
98202                     break;
98203                 case 225 /* VariableStatement */:
98204                     generateNames(node.declarationList);
98205                     break;
98206                 case 243 /* VariableDeclarationList */:
98207                     ts.forEach(node.declarations, generateNames);
98208                     break;
98209                 case 242 /* VariableDeclaration */:
98210                 case 156 /* Parameter */:
98211                 case 191 /* BindingElement */:
98212                 case 245 /* ClassDeclaration */:
98213                     generateNameIfNeeded(node.name);
98214                     break;
98215                 case 244 /* FunctionDeclaration */:
98216                     generateNameIfNeeded(node.name);
98217                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98218                         ts.forEach(node.parameters, generateNames);
98219                         generateNames(node.body);
98220                     }
98221                     break;
98222                 case 189 /* ObjectBindingPattern */:
98223                 case 190 /* ArrayBindingPattern */:
98224                     ts.forEach(node.elements, generateNames);
98225                     break;
98226                 case 254 /* ImportDeclaration */:
98227                     generateNames(node.importClause);
98228                     break;
98229                 case 255 /* ImportClause */:
98230                     generateNameIfNeeded(node.name);
98231                     generateNames(node.namedBindings);
98232                     break;
98233                 case 256 /* NamespaceImport */:
98234                     generateNameIfNeeded(node.name);
98235                     break;
98236                 case 262 /* NamespaceExport */:
98237                     generateNameIfNeeded(node.name);
98238                     break;
98239                 case 257 /* NamedImports */:
98240                     ts.forEach(node.elements, generateNames);
98241                     break;
98242                 case 258 /* ImportSpecifier */:
98243                     generateNameIfNeeded(node.propertyName || node.name);
98244                     break;
98245             }
98246         }
98247         function generateMemberNames(node) {
98248             if (!node)
98249                 return;
98250             switch (node.kind) {
98251                 case 281 /* PropertyAssignment */:
98252                 case 282 /* ShorthandPropertyAssignment */:
98253                 case 159 /* PropertyDeclaration */:
98254                 case 161 /* MethodDeclaration */:
98255                 case 163 /* GetAccessor */:
98256                 case 164 /* SetAccessor */:
98257                     generateNameIfNeeded(node.name);
98258                     break;
98259             }
98260         }
98261         function generateNameIfNeeded(name) {
98262             if (name) {
98263                 if (ts.isGeneratedIdentifier(name)) {
98264                     generateName(name);
98265                 }
98266                 else if (ts.isBindingPattern(name)) {
98267                     generateNames(name);
98268                 }
98269             }
98270         }
98271         /**
98272          * Generate the text for a generated identifier.
98273          */
98274         function generateName(name) {
98275             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98276                 // Node names generate unique names based on their original node
98277                 // and are cached based on that node's id.
98278                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98279             }
98280             else {
98281                 // Auto, Loop, and Unique names are cached based on their unique
98282                 // autoGenerateId.
98283                 var autoGenerateId = name.autoGenerateId;
98284                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98285             }
98286         }
98287         function generateNameCached(node, flags) {
98288             var nodeId = ts.getNodeId(node);
98289             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98290         }
98291         /**
98292          * Returns a value indicating whether a name is unique globally, within the current file,
98293          * or within the NameGenerator.
98294          */
98295         function isUniqueName(name) {
98296             return isFileLevelUniqueName(name)
98297                 && !generatedNames.has(name)
98298                 && !(reservedNames && reservedNames.has(name));
98299         }
98300         /**
98301          * Returns a value indicating whether a name is unique globally or within the current file.
98302          */
98303         function isFileLevelUniqueName(name) {
98304             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98305         }
98306         /**
98307          * Returns a value indicating whether a name is unique within a container.
98308          */
98309         function isUniqueLocalName(name, container) {
98310             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98311                 if (node.locals) {
98312                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98313                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98314                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98315                         return false;
98316                     }
98317                 }
98318             }
98319             return true;
98320         }
98321         /**
98322          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98323          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98324          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98325          */
98326         function makeTempVariableName(flags, reservedInNestedScopes) {
98327             if (flags && !(tempFlags & flags)) {
98328                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98329                 if (isUniqueName(name)) {
98330                     tempFlags |= flags;
98331                     if (reservedInNestedScopes) {
98332                         reserveNameInNestedScopes(name);
98333                     }
98334                     return name;
98335                 }
98336             }
98337             while (true) {
98338                 var count = tempFlags & 268435455 /* CountMask */;
98339                 tempFlags++;
98340                 // Skip over 'i' and 'n'
98341                 if (count !== 8 && count !== 13) {
98342                     var name = count < 26
98343                         ? "_" + String.fromCharCode(97 /* a */ + count)
98344                         : "_" + (count - 26);
98345                     if (isUniqueName(name)) {
98346                         if (reservedInNestedScopes) {
98347                             reserveNameInNestedScopes(name);
98348                         }
98349                         return name;
98350                     }
98351                 }
98352             }
98353         }
98354         /**
98355          * Generate a name that is unique within the current file and doesn't conflict with any names
98356          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98357          * where n is a positive integer. Note that names generated by makeTempVariableName and
98358          * makeUniqueName are guaranteed to never conflict.
98359          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98360          */
98361         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98362             if (checkFn === void 0) { checkFn = isUniqueName; }
98363             if (optimistic) {
98364                 if (checkFn(baseName)) {
98365                     if (scoped) {
98366                         reserveNameInNestedScopes(baseName);
98367                     }
98368                     else {
98369                         generatedNames.set(baseName, true);
98370                     }
98371                     return baseName;
98372                 }
98373             }
98374             // Find the first unique 'name_n', where n is a positive number
98375             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98376                 baseName += "_";
98377             }
98378             var i = 1;
98379             while (true) {
98380                 var generatedName = baseName + i;
98381                 if (checkFn(generatedName)) {
98382                     if (scoped) {
98383                         reserveNameInNestedScopes(generatedName);
98384                     }
98385                     else {
98386                         generatedNames.set(generatedName, true);
98387                     }
98388                     return generatedName;
98389                 }
98390                 i++;
98391             }
98392         }
98393         function makeFileLevelOptimisticUniqueName(name) {
98394             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98395         }
98396         /**
98397          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98398          */
98399         function generateNameForModuleOrEnum(node) {
98400             var name = getTextOfNode(node.name);
98401             // Use module/enum name itself if it is unique, otherwise make a unique variation
98402             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98403         }
98404         /**
98405          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98406          */
98407         function generateNameForImportOrExportDeclaration(node) {
98408             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98409             var baseName = ts.isStringLiteral(expr) ?
98410                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98411             return makeUniqueName(baseName);
98412         }
98413         /**
98414          * Generates a unique name for a default export.
98415          */
98416         function generateNameForExportDefault() {
98417             return makeUniqueName("default");
98418         }
98419         /**
98420          * Generates a unique name for a class expression.
98421          */
98422         function generateNameForClassExpression() {
98423             return makeUniqueName("class");
98424         }
98425         function generateNameForMethodOrAccessor(node) {
98426             if (ts.isIdentifier(node.name)) {
98427                 return generateNameCached(node.name);
98428             }
98429             return makeTempVariableName(0 /* Auto */);
98430         }
98431         /**
98432          * Generates a unique name from a node.
98433          */
98434         function generateNameForNode(node, flags) {
98435             switch (node.kind) {
98436                 case 75 /* Identifier */:
98437                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98438                 case 249 /* ModuleDeclaration */:
98439                 case 248 /* EnumDeclaration */:
98440                     return generateNameForModuleOrEnum(node);
98441                 case 254 /* ImportDeclaration */:
98442                 case 260 /* ExportDeclaration */:
98443                     return generateNameForImportOrExportDeclaration(node);
98444                 case 244 /* FunctionDeclaration */:
98445                 case 245 /* ClassDeclaration */:
98446                 case 259 /* ExportAssignment */:
98447                     return generateNameForExportDefault();
98448                 case 214 /* ClassExpression */:
98449                     return generateNameForClassExpression();
98450                 case 161 /* MethodDeclaration */:
98451                 case 163 /* GetAccessor */:
98452                 case 164 /* SetAccessor */:
98453                     return generateNameForMethodOrAccessor(node);
98454                 case 154 /* ComputedPropertyName */:
98455                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98456                 default:
98457                     return makeTempVariableName(0 /* Auto */);
98458             }
98459         }
98460         /**
98461          * Generates a unique identifier for a node.
98462          */
98463         function makeName(name) {
98464             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98465                 case 1 /* Auto */:
98466                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98467                 case 2 /* Loop */:
98468                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98469                 case 3 /* Unique */:
98470                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98471             }
98472             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98473         }
98474         /**
98475          * Gets the node from which a name should be generated.
98476          */
98477         function getNodeForGeneratedName(name) {
98478             var autoGenerateId = name.autoGenerateId;
98479             var node = name;
98480             var original = node.original;
98481             while (original) {
98482                 node = original;
98483                 // if "node" is a different generated name (having a different
98484                 // "autoGenerateId"), use it and stop traversing.
98485                 if (ts.isIdentifier(node)
98486                     && !!(node.autoGenerateFlags & 4 /* Node */)
98487                     && node.autoGenerateId !== autoGenerateId) {
98488                     break;
98489                 }
98490                 original = node.original;
98491             }
98492             // otherwise, return the original node for the source;
98493             return node;
98494         }
98495         // Comments
98496         function pipelineEmitWithComments(hint, node) {
98497             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98498             enterComment();
98499             hasWrittenComment = false;
98500             var emitFlags = ts.getEmitFlags(node);
98501             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98502             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98503             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98504             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98505             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98506             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98507             // Save current container state on the stack.
98508             var savedContainerPos = containerPos;
98509             var savedContainerEnd = containerEnd;
98510             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98511             if ((pos > 0 || end > 0) && pos !== end) {
98512                 // Emit leading comments if the position is not synthesized and the node
98513                 // has not opted out from emitting leading comments.
98514                 if (!skipLeadingComments) {
98515                     emitLeadingComments(pos, isEmittedNode);
98516                 }
98517                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98518                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98519                     containerPos = pos;
98520                 }
98521                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98522                     // As above.
98523                     containerEnd = end;
98524                     // To avoid invalid comment emit in a down-level binding pattern, we
98525                     // keep track of the last declaration list container's end
98526                     if (node.kind === 243 /* VariableDeclarationList */) {
98527                         declarationListContainerEnd = end;
98528                     }
98529                 }
98530             }
98531             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98532             exitComment();
98533             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98534             if (emitFlags & 2048 /* NoNestedComments */) {
98535                 commentsDisabled = true;
98536                 pipelinePhase(hint, node);
98537                 commentsDisabled = false;
98538             }
98539             else {
98540                 pipelinePhase(hint, node);
98541             }
98542             enterComment();
98543             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98544             if ((pos > 0 || end > 0) && pos !== end) {
98545                 // Restore previous container state.
98546                 containerPos = savedContainerPos;
98547                 containerEnd = savedContainerEnd;
98548                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98549                 // Emit trailing comments if the position is not synthesized and the node
98550                 // has not opted out from emitting leading comments and is an emitted node.
98551                 if (!skipTrailingComments && isEmittedNode) {
98552                     emitTrailingComments(end);
98553                 }
98554             }
98555             exitComment();
98556             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98557         }
98558         function emitLeadingSynthesizedComment(comment) {
98559             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98560                 writer.writeLine();
98561             }
98562             writeSynthesizedComment(comment);
98563             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98564                 writer.writeLine();
98565             }
98566             else {
98567                 writer.writeSpace(" ");
98568             }
98569         }
98570         function emitTrailingSynthesizedComment(comment) {
98571             if (!writer.isAtStartOfLine()) {
98572                 writer.writeSpace(" ");
98573             }
98574             writeSynthesizedComment(comment);
98575             if (comment.hasTrailingNewLine) {
98576                 writer.writeLine();
98577             }
98578         }
98579         function writeSynthesizedComment(comment) {
98580             var text = formatSynthesizedComment(comment);
98581             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98582             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98583         }
98584         function formatSynthesizedComment(comment) {
98585             return comment.kind === 3 /* MultiLineCommentTrivia */
98586                 ? "/*" + comment.text + "*/"
98587                 : "//" + comment.text;
98588         }
98589         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98590             enterComment();
98591             var pos = detachedRange.pos, end = detachedRange.end;
98592             var emitFlags = ts.getEmitFlags(node);
98593             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98594             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98595             if (!skipLeadingComments) {
98596                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98597             }
98598             exitComment();
98599             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98600                 commentsDisabled = true;
98601                 emitCallback(node);
98602                 commentsDisabled = false;
98603             }
98604             else {
98605                 emitCallback(node);
98606             }
98607             enterComment();
98608             if (!skipTrailingComments) {
98609                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98610                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98611                     writer.writeLine();
98612                 }
98613             }
98614             exitComment();
98615         }
98616         function emitLeadingComments(pos, isEmittedNode) {
98617             hasWrittenComment = false;
98618             if (isEmittedNode) {
98619                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98620             }
98621             else if (pos === 0) {
98622                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98623                 // unless it is a triple slash comment at the top of the file.
98624                 // For Example:
98625                 //      /// <reference-path ...>
98626                 //      declare var x;
98627                 //      /// <reference-path ...>
98628                 //      interface F {}
98629                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98630                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98631             }
98632         }
98633         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98634             if (isTripleSlashComment(commentPos, commentEnd)) {
98635                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98636             }
98637         }
98638         function shouldWriteComment(text, pos) {
98639             if (printerOptions.onlyPrintJsDocStyle) {
98640                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98641             }
98642             return true;
98643         }
98644         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98645             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98646                 return;
98647             if (!hasWrittenComment) {
98648                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98649                 hasWrittenComment = true;
98650             }
98651             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98652             emitPos(commentPos);
98653             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98654             emitPos(commentEnd);
98655             if (hasTrailingNewLine) {
98656                 writer.writeLine();
98657             }
98658             else if (kind === 3 /* MultiLineCommentTrivia */) {
98659                 writer.writeSpace(" ");
98660             }
98661         }
98662         function emitLeadingCommentsOfPosition(pos) {
98663             if (commentsDisabled || pos === -1) {
98664                 return;
98665             }
98666             emitLeadingComments(pos, /*isEmittedNode*/ true);
98667         }
98668         function emitTrailingComments(pos) {
98669             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98670         }
98671         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98672             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98673                 return;
98674             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98675             if (!writer.isAtStartOfLine()) {
98676                 writer.writeSpace(" ");
98677             }
98678             emitPos(commentPos);
98679             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98680             emitPos(commentEnd);
98681             if (hasTrailingNewLine) {
98682                 writer.writeLine();
98683             }
98684         }
98685         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98686             if (commentsDisabled) {
98687                 return;
98688             }
98689             enterComment();
98690             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98691             exitComment();
98692         }
98693         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98694             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98695             emitPos(commentPos);
98696             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98697             emitPos(commentEnd);
98698             if (hasTrailingNewLine) {
98699                 writer.writeLine();
98700             }
98701             else {
98702                 writer.writeSpace(" ");
98703             }
98704         }
98705         function forEachLeadingCommentToEmit(pos, cb) {
98706             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98707             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98708                 if (hasDetachedComments(pos)) {
98709                     forEachLeadingCommentWithoutDetachedComments(cb);
98710                 }
98711                 else {
98712                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98713                 }
98714             }
98715         }
98716         function forEachTrailingCommentToEmit(end, cb) {
98717             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98718             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98719                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98720             }
98721         }
98722         function hasDetachedComments(pos) {
98723             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98724         }
98725         function forEachLeadingCommentWithoutDetachedComments(cb) {
98726             // get the leading comments from detachedPos
98727             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98728             if (detachedCommentsInfo.length - 1) {
98729                 detachedCommentsInfo.pop();
98730             }
98731             else {
98732                 detachedCommentsInfo = undefined;
98733             }
98734             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98735         }
98736         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98737             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98738             if (currentDetachedCommentInfo) {
98739                 if (detachedCommentsInfo) {
98740                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98741                 }
98742                 else {
98743                     detachedCommentsInfo = [currentDetachedCommentInfo];
98744                 }
98745             }
98746         }
98747         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98748             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98749                 return;
98750             emitPos(commentPos);
98751             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98752             emitPos(commentEnd);
98753         }
98754         /**
98755          * Determine if the given comment is a triple-slash
98756          *
98757          * @return true if the comment is a triple-slash comment else false
98758          */
98759         function isTripleSlashComment(commentPos, commentEnd) {
98760             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98761         }
98762         // Source Maps
98763         function getParsedSourceMap(node) {
98764             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98765                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98766             }
98767             return node.parsedSourceMap || undefined;
98768         }
98769         function pipelineEmitWithSourceMap(hint, node) {
98770             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98771             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98772             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98773                 pipelinePhase(hint, node);
98774             }
98775             else if (ts.isUnparsedNode(node)) {
98776                 var parsed = getParsedSourceMap(node.parent);
98777                 if (parsed && sourceMapGenerator) {
98778                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98779                 }
98780                 pipelinePhase(hint, node);
98781             }
98782             else {
98783                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98784                 var emitFlags = ts.getEmitFlags(node);
98785                 if (node.kind !== 325 /* NotEmittedStatement */
98786                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98787                     && pos >= 0) {
98788                     emitSourcePos(source, skipSourceTrivia(source, pos));
98789                 }
98790                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98791                     sourceMapsDisabled = true;
98792                     pipelinePhase(hint, node);
98793                     sourceMapsDisabled = false;
98794                 }
98795                 else {
98796                     pipelinePhase(hint, node);
98797                 }
98798                 if (node.kind !== 325 /* NotEmittedStatement */
98799                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98800                     && end >= 0) {
98801                     emitSourcePos(source, end);
98802                 }
98803             }
98804             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98805         }
98806         /**
98807          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98808          */
98809         function skipSourceTrivia(source, pos) {
98810             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98811         }
98812         /**
98813          * Emits a mapping.
98814          *
98815          * If the position is synthetic (undefined or a negative value), no mapping will be
98816          * created.
98817          *
98818          * @param pos The position.
98819          */
98820         function emitPos(pos) {
98821             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
98822                 return;
98823             }
98824             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
98825             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
98826             /*nameIndex*/ undefined);
98827         }
98828         function emitSourcePos(source, pos) {
98829             if (source !== sourceMapSource) {
98830                 var savedSourceMapSource = sourceMapSource;
98831                 setSourceMapSource(source);
98832                 emitPos(pos);
98833                 setSourceMapSource(savedSourceMapSource);
98834             }
98835             else {
98836                 emitPos(pos);
98837             }
98838         }
98839         /**
98840          * Emits a token of a node with possible leading and trailing source maps.
98841          *
98842          * @param node The node containing the token.
98843          * @param token The token to emit.
98844          * @param tokenStartPos The start pos of the token.
98845          * @param emitCallback The callback used to emit the token.
98846          */
98847         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
98848             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
98849                 return emitCallback(token, writer, tokenPos);
98850             }
98851             var emitNode = node && node.emitNode;
98852             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
98853             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
98854             var source = range && range.source || sourceMapSource;
98855             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
98856             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
98857                 emitSourcePos(source, tokenPos);
98858             }
98859             tokenPos = emitCallback(token, writer, tokenPos);
98860             if (range)
98861                 tokenPos = range.end;
98862             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
98863                 emitSourcePos(source, tokenPos);
98864             }
98865             return tokenPos;
98866         }
98867         function setSourceMapSource(source) {
98868             if (sourceMapsDisabled) {
98869                 return;
98870             }
98871             sourceMapSource = source;
98872             if (isJsonSourceMapSource(source)) {
98873                 return;
98874             }
98875             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
98876             if (printerOptions.inlineSources) {
98877                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
98878             }
98879         }
98880         function isJsonSourceMapSource(sourceFile) {
98881             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
98882         }
98883     }
98884     ts.createPrinter = createPrinter;
98885     function createBracketsMap() {
98886         var brackets = [];
98887         brackets[1024 /* Braces */] = ["{", "}"];
98888         brackets[2048 /* Parenthesis */] = ["(", ")"];
98889         brackets[4096 /* AngleBrackets */] = ["<", ">"];
98890         brackets[8192 /* SquareBrackets */] = ["[", "]"];
98891         return brackets;
98892     }
98893     function getOpeningBracket(format) {
98894         return brackets[format & 15360 /* BracketsMask */][0];
98895     }
98896     function getClosingBracket(format) {
98897         return brackets[format & 15360 /* BracketsMask */][1];
98898     }
98899     // Flags enum to track count of temp variables and a few dedicated names
98900     var TempFlags;
98901     (function (TempFlags) {
98902         TempFlags[TempFlags["Auto"] = 0] = "Auto";
98903         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
98904         TempFlags[TempFlags["_i"] = 268435456] = "_i";
98905     })(TempFlags || (TempFlags = {}));
98906 })(ts || (ts = {}));
98907 /* @internal */
98908 var ts;
98909 (function (ts) {
98910     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
98911         if (!host.getDirectories || !host.readDirectory) {
98912             return undefined;
98913         }
98914         var cachedReadDirectoryResult = ts.createMap();
98915         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
98916         return {
98917             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
98918             fileExists: fileExists,
98919             readFile: function (path, encoding) { return host.readFile(path, encoding); },
98920             directoryExists: host.directoryExists && directoryExists,
98921             getDirectories: getDirectories,
98922             readDirectory: readDirectory,
98923             createDirectory: host.createDirectory && createDirectory,
98924             writeFile: host.writeFile && writeFile,
98925             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
98926             addOrDeleteFile: addOrDeleteFile,
98927             clearCache: clearCache,
98928             realpath: host.realpath && realpath
98929         };
98930         function toPath(fileName) {
98931             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
98932         }
98933         function getCachedFileSystemEntries(rootDirPath) {
98934             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
98935         }
98936         function getCachedFileSystemEntriesForBaseDir(path) {
98937             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
98938         }
98939         function getBaseNameOfFileName(fileName) {
98940             return ts.getBaseFileName(ts.normalizePath(fileName));
98941         }
98942         function createCachedFileSystemEntries(rootDir, rootDirPath) {
98943             var resultFromHost = {
98944                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
98945                 directories: host.getDirectories(rootDir) || []
98946             };
98947             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
98948             return resultFromHost;
98949         }
98950         /**
98951          * If the readDirectory result was already cached, it returns that
98952          * Otherwise gets result from host and caches it.
98953          * The host request is done under try catch block to avoid caching incorrect result
98954          */
98955         function tryReadDirectory(rootDir, rootDirPath) {
98956             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
98957             var cachedResult = getCachedFileSystemEntries(rootDirPath);
98958             if (cachedResult) {
98959                 return cachedResult;
98960             }
98961             try {
98962                 return createCachedFileSystemEntries(rootDir, rootDirPath);
98963             }
98964             catch (_e) {
98965                 // If there is exception to read directories, dont cache the result and direct the calls to host
98966                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
98967                 return undefined;
98968             }
98969         }
98970         function fileNameEqual(name1, name2) {
98971             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
98972         }
98973         function hasEntry(entries, name) {
98974             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
98975         }
98976         function updateFileSystemEntry(entries, baseName, isValid) {
98977             if (hasEntry(entries, baseName)) {
98978                 if (!isValid) {
98979                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
98980                 }
98981             }
98982             else if (isValid) {
98983                 return entries.push(baseName);
98984             }
98985         }
98986         function writeFile(fileName, data, writeByteOrderMark) {
98987             var path = toPath(fileName);
98988             var result = getCachedFileSystemEntriesForBaseDir(path);
98989             if (result) {
98990                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
98991             }
98992             return host.writeFile(fileName, data, writeByteOrderMark);
98993         }
98994         function fileExists(fileName) {
98995             var path = toPath(fileName);
98996             var result = getCachedFileSystemEntriesForBaseDir(path);
98997             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
98998                 host.fileExists(fileName);
98999         }
99000         function directoryExists(dirPath) {
99001             var path = toPath(dirPath);
99002             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99003         }
99004         function createDirectory(dirPath) {
99005             var path = toPath(dirPath);
99006             var result = getCachedFileSystemEntriesForBaseDir(path);
99007             var baseFileName = getBaseNameOfFileName(dirPath);
99008             if (result) {
99009                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99010             }
99011             host.createDirectory(dirPath);
99012         }
99013         function getDirectories(rootDir) {
99014             var rootDirPath = toPath(rootDir);
99015             var result = tryReadDirectory(rootDir, rootDirPath);
99016             if (result) {
99017                 return result.directories.slice();
99018             }
99019             return host.getDirectories(rootDir);
99020         }
99021         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99022             var rootDirPath = toPath(rootDir);
99023             var result = tryReadDirectory(rootDir, rootDirPath);
99024             if (result) {
99025                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99026             }
99027             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99028             function getFileSystemEntries(dir) {
99029                 var path = toPath(dir);
99030                 if (path === rootDirPath) {
99031                     return result;
99032                 }
99033                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99034             }
99035         }
99036         function realpath(s) {
99037             return host.realpath ? host.realpath(s) : s;
99038         }
99039         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99040             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99041             if (existingResult) {
99042                 // Just clear the cache for now
99043                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99044                 clearCache();
99045                 return undefined;
99046             }
99047             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99048             if (!parentResult) {
99049                 return undefined;
99050             }
99051             // This was earlier a file (hence not in cached directory contents)
99052             // or we never cached the directory containing it
99053             if (!host.directoryExists) {
99054                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99055                 clearCache();
99056                 return undefined;
99057             }
99058             var baseName = getBaseNameOfFileName(fileOrDirectory);
99059             var fsQueryResult = {
99060                 fileExists: host.fileExists(fileOrDirectoryPath),
99061                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99062             };
99063             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99064                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99065                 clearCache();
99066             }
99067             else {
99068                 // No need to update the directory structure, just files
99069                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99070             }
99071             return fsQueryResult;
99072         }
99073         function addOrDeleteFile(fileName, filePath, eventKind) {
99074             if (eventKind === ts.FileWatcherEventKind.Changed) {
99075                 return;
99076             }
99077             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99078             if (parentResult) {
99079                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99080             }
99081         }
99082         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99083             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99084         }
99085         function clearCache() {
99086             cachedReadDirectoryResult.clear();
99087         }
99088     }
99089     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99090     var ConfigFileProgramReloadLevel;
99091     (function (ConfigFileProgramReloadLevel) {
99092         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99093         /** Update the file name list from the disk */
99094         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99095         /** Reload completely by re-reading contents of config file from disk and updating program */
99096         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99097     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99098     /**
99099      * Updates the existing missing file watches with the new set of missing files after new program is created
99100      */
99101     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99102         var missingFilePaths = program.getMissingFilePaths();
99103         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99104         // Update the missing file paths watcher
99105         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99106             // Watch the missing files
99107             createNewValue: createMissingFileWatch,
99108             // Files that are no longer missing (e.g. because they are no longer required)
99109             // should no longer be watched.
99110             onDeleteValue: ts.closeFileWatcher
99111         });
99112     }
99113     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99114     /**
99115      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99116      * after new program is created because the config file was reloaded or program was created first time from the config file
99117      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99118      * as wildcard directories wont change unless reloading config file
99119      */
99120     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99121         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99122             // Create new watch and recursive info
99123             createNewValue: createWildcardDirectoryWatcher,
99124             // Close existing watch thats not needed any more
99125             onDeleteValue: closeFileWatcherOf,
99126             // Close existing watch that doesnt match in the flags
99127             onExistingValue: updateWildcardDirectoryWatcher
99128         });
99129         function createWildcardDirectoryWatcher(directory, flags) {
99130             // Create new watch and recursive info
99131             return {
99132                 watcher: watchDirectory(directory, flags),
99133                 flags: flags
99134             };
99135         }
99136         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99137             // Watcher needs to be updated if the recursive flags dont match
99138             if (existingWatcher.flags === flags) {
99139                 return;
99140             }
99141             existingWatcher.watcher.close();
99142             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99143         }
99144     }
99145     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99146     function isEmittedFileOfProgram(program, file) {
99147         if (!program) {
99148             return false;
99149         }
99150         return program.isEmittedFile(file);
99151     }
99152     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99153     var WatchLogLevel;
99154     (function (WatchLogLevel) {
99155         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99156         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99157         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99158     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99159     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99160         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99161     }
99162     ts.getWatchFactory = getWatchFactory;
99163     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99164         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99165         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99166         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99167         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99168             ts.setSysLog(function (s) { return log(s); });
99169         }
99170         return {
99171             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99172                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99173             },
99174             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99175                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99176             },
99177             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99178                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99179             }
99180         };
99181     }
99182     function watchFile(host, file, callback, pollingInterval, options) {
99183         return host.watchFile(file, callback, pollingInterval, options);
99184     }
99185     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99186         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99187     }
99188     function watchDirectory(host, directory, callback, flags, options) {
99189         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99190     }
99191     function getCreateFileWatcher(watchLogLevel, addWatch) {
99192         switch (watchLogLevel) {
99193             case WatchLogLevel.None:
99194                 return addWatch;
99195             case WatchLogLevel.TriggerOnly:
99196                 return createFileWatcherWithTriggerLogging;
99197             case WatchLogLevel.Verbose:
99198                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99199         }
99200     }
99201     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99202         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99203         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99204         return {
99205             close: function () {
99206                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99207                 watcher.close();
99208             }
99209         };
99210     }
99211     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99212         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99213         log(watchInfo);
99214         var start = ts.timestamp();
99215         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99216         var elapsed = ts.timestamp() - start;
99217         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99218         return {
99219             close: function () {
99220                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99221                 log(watchInfo);
99222                 var start = ts.timestamp();
99223                 watcher.close();
99224                 var elapsed = ts.timestamp() - start;
99225                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99226             }
99227         };
99228     }
99229     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99230         return addWatch(host, file, function (fileName, cbOptional) {
99231             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99232             log(triggerredInfo);
99233             var start = ts.timestamp();
99234             cb(fileName, cbOptional, passThrough);
99235             var elapsed = ts.timestamp() - start;
99236             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99237         }, flags, options);
99238     }
99239     function getFallbackOptions(options) {
99240         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99241         return {
99242             watchFile: fallbackPolling !== undefined ?
99243                 fallbackPolling :
99244                 ts.WatchFileKind.PriorityPollingInterval
99245         };
99246     }
99247     ts.getFallbackOptions = getFallbackOptions;
99248     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99249         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99250     }
99251     function closeFileWatcherOf(objWithWatcher) {
99252         objWithWatcher.watcher.close();
99253     }
99254     ts.closeFileWatcherOf = closeFileWatcherOf;
99255 })(ts || (ts = {}));
99256 var ts;
99257 (function (ts) {
99258     function findConfigFile(searchPath, fileExists, configName) {
99259         if (configName === void 0) { configName = "tsconfig.json"; }
99260         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99261             var fileName = ts.combinePaths(ancestor, configName);
99262             return fileExists(fileName) ? fileName : undefined;
99263         });
99264     }
99265     ts.findConfigFile = findConfigFile;
99266     function resolveTripleslashReference(moduleName, containingFile) {
99267         var basePath = ts.getDirectoryPath(containingFile);
99268         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99269         return ts.normalizePath(referencedFileName);
99270     }
99271     ts.resolveTripleslashReference = resolveTripleslashReference;
99272     /* @internal */
99273     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99274         var commonPathComponents;
99275         var failed = ts.forEach(fileNames, function (sourceFile) {
99276             // Each file contributes into common source file path
99277             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99278             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99279             if (!commonPathComponents) {
99280                 // first file
99281                 commonPathComponents = sourcePathComponents;
99282                 return;
99283             }
99284             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99285             for (var i = 0; i < n; i++) {
99286                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99287                     if (i === 0) {
99288                         // Failed to find any common path component
99289                         return true;
99290                     }
99291                     // New common path found that is 0 -> i-1
99292                     commonPathComponents.length = i;
99293                     break;
99294                 }
99295             }
99296             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99297             if (sourcePathComponents.length < commonPathComponents.length) {
99298                 commonPathComponents.length = sourcePathComponents.length;
99299             }
99300         });
99301         // A common path can not be found when paths span multiple drives on windows, for example
99302         if (failed) {
99303             return "";
99304         }
99305         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99306             return currentDirectory;
99307         }
99308         return ts.getPathFromPathComponents(commonPathComponents);
99309     }
99310     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99311     function createCompilerHost(options, setParentNodes) {
99312         return createCompilerHostWorker(options, setParentNodes);
99313     }
99314     ts.createCompilerHost = createCompilerHost;
99315     /*@internal*/
99316     // TODO(shkamat): update this after reworking ts build API
99317     function createCompilerHostWorker(options, setParentNodes, system) {
99318         if (system === void 0) { system = ts.sys; }
99319         var existingDirectories = ts.createMap();
99320         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99321         function getSourceFile(fileName, languageVersion, onError) {
99322             var text;
99323             try {
99324                 ts.performance.mark("beforeIORead");
99325                 text = compilerHost.readFile(fileName);
99326                 ts.performance.mark("afterIORead");
99327                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99328             }
99329             catch (e) {
99330                 if (onError) {
99331                     onError(e.message);
99332                 }
99333                 text = "";
99334             }
99335             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99336         }
99337         function directoryExists(directoryPath) {
99338             if (existingDirectories.has(directoryPath)) {
99339                 return true;
99340             }
99341             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99342                 existingDirectories.set(directoryPath, true);
99343                 return true;
99344             }
99345             return false;
99346         }
99347         function writeFile(fileName, data, writeByteOrderMark, onError) {
99348             try {
99349                 ts.performance.mark("beforeIOWrite");
99350                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99351                 // the system.writeFile will do its own directory creation and
99352                 // the ensureDirectoriesExist call will always be redundant.
99353                 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); });
99354                 ts.performance.mark("afterIOWrite");
99355                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99356             }
99357             catch (e) {
99358                 if (onError) {
99359                     onError(e.message);
99360                 }
99361             }
99362         }
99363         var outputFingerprints;
99364         function writeFileWorker(fileName, data, writeByteOrderMark) {
99365             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99366                 system.writeFile(fileName, data, writeByteOrderMark);
99367                 return;
99368             }
99369             if (!outputFingerprints) {
99370                 outputFingerprints = ts.createMap();
99371             }
99372             var hash = system.createHash(data);
99373             var mtimeBefore = system.getModifiedTime(fileName);
99374             if (mtimeBefore) {
99375                 var fingerprint = outputFingerprints.get(fileName);
99376                 // If output has not been changed, and the file has no external modification
99377                 if (fingerprint &&
99378                     fingerprint.byteOrderMark === writeByteOrderMark &&
99379                     fingerprint.hash === hash &&
99380                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99381                     return;
99382                 }
99383             }
99384             system.writeFile(fileName, data, writeByteOrderMark);
99385             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99386             outputFingerprints.set(fileName, {
99387                 hash: hash,
99388                 byteOrderMark: writeByteOrderMark,
99389                 mtime: mtimeAfter
99390             });
99391         }
99392         function getDefaultLibLocation() {
99393             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99394         }
99395         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99396         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99397         var compilerHost = {
99398             getSourceFile: getSourceFile,
99399             getDefaultLibLocation: getDefaultLibLocation,
99400             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99401             writeFile: writeFile,
99402             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99403             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99404             getCanonicalFileName: getCanonicalFileName,
99405             getNewLine: function () { return newLine; },
99406             fileExists: function (fileName) { return system.fileExists(fileName); },
99407             readFile: function (fileName) { return system.readFile(fileName); },
99408             trace: function (s) { return system.write(s + newLine); },
99409             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99410             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99411             getDirectories: function (path) { return system.getDirectories(path); },
99412             realpath: realpath,
99413             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99414             createDirectory: function (d) { return system.createDirectory(d); },
99415             createHash: ts.maybeBind(system, system.createHash)
99416         };
99417         return compilerHost;
99418     }
99419     ts.createCompilerHostWorker = createCompilerHostWorker;
99420     /*@internal*/
99421     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99422         var originalReadFile = host.readFile;
99423         var originalFileExists = host.fileExists;
99424         var originalDirectoryExists = host.directoryExists;
99425         var originalCreateDirectory = host.createDirectory;
99426         var originalWriteFile = host.writeFile;
99427         var readFileCache = ts.createMap();
99428         var fileExistsCache = ts.createMap();
99429         var directoryExistsCache = ts.createMap();
99430         var sourceFileCache = ts.createMap();
99431         var readFileWithCache = function (fileName) {
99432             var key = toPath(fileName);
99433             var value = readFileCache.get(key);
99434             if (value !== undefined)
99435                 return value !== false ? value : undefined;
99436             return setReadFileCache(key, fileName);
99437         };
99438         var setReadFileCache = function (key, fileName) {
99439             var newValue = originalReadFile.call(host, fileName);
99440             readFileCache.set(key, newValue !== undefined ? newValue : false);
99441             return newValue;
99442         };
99443         host.readFile = function (fileName) {
99444             var key = toPath(fileName);
99445             var value = readFileCache.get(key);
99446             if (value !== undefined)
99447                 return value !== false ? value : undefined; // could be .d.ts from output
99448             // Cache json or buildInfo
99449             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99450                 return originalReadFile.call(host, fileName);
99451             }
99452             return setReadFileCache(key, fileName);
99453         };
99454         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99455             var key = toPath(fileName);
99456             var value = sourceFileCache.get(key);
99457             if (value)
99458                 return value;
99459             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99460             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99461                 sourceFileCache.set(key, sourceFile);
99462             }
99463             return sourceFile;
99464         } : undefined;
99465         // fileExists for any kind of extension
99466         host.fileExists = function (fileName) {
99467             var key = toPath(fileName);
99468             var value = fileExistsCache.get(key);
99469             if (value !== undefined)
99470                 return value;
99471             var newValue = originalFileExists.call(host, fileName);
99472             fileExistsCache.set(key, !!newValue);
99473             return newValue;
99474         };
99475         if (originalWriteFile) {
99476             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99477                 var key = toPath(fileName);
99478                 fileExistsCache.delete(key);
99479                 var value = readFileCache.get(key);
99480                 if (value !== undefined && value !== data) {
99481                     readFileCache.delete(key);
99482                     sourceFileCache.delete(key);
99483                 }
99484                 else if (getSourceFileWithCache) {
99485                     var sourceFile = sourceFileCache.get(key);
99486                     if (sourceFile && sourceFile.text !== data) {
99487                         sourceFileCache.delete(key);
99488                     }
99489                 }
99490                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99491             };
99492         }
99493         // directoryExists
99494         if (originalDirectoryExists && originalCreateDirectory) {
99495             host.directoryExists = function (directory) {
99496                 var key = toPath(directory);
99497                 var value = directoryExistsCache.get(key);
99498                 if (value !== undefined)
99499                     return value;
99500                 var newValue = originalDirectoryExists.call(host, directory);
99501                 directoryExistsCache.set(key, !!newValue);
99502                 return newValue;
99503             };
99504             host.createDirectory = function (directory) {
99505                 var key = toPath(directory);
99506                 directoryExistsCache.delete(key);
99507                 originalCreateDirectory.call(host, directory);
99508             };
99509         }
99510         return {
99511             originalReadFile: originalReadFile,
99512             originalFileExists: originalFileExists,
99513             originalDirectoryExists: originalDirectoryExists,
99514             originalCreateDirectory: originalCreateDirectory,
99515             originalWriteFile: originalWriteFile,
99516             getSourceFileWithCache: getSourceFileWithCache,
99517             readFileWithCache: readFileWithCache
99518         };
99519     }
99520     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99521     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99522         var diagnostics;
99523         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99524         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99525         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99526         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99527         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99528         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99529             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99530         }
99531         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99532     }
99533     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99534     function formatDiagnostics(diagnostics, host) {
99535         var output = "";
99536         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99537             var diagnostic = diagnostics_2[_i];
99538             output += formatDiagnostic(diagnostic, host);
99539         }
99540         return output;
99541     }
99542     ts.formatDiagnostics = formatDiagnostics;
99543     function formatDiagnostic(diagnostic, host) {
99544         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99545         if (diagnostic.file) {
99546             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99547             var fileName = diagnostic.file.fileName;
99548             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99549             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99550         }
99551         return errorMessage;
99552     }
99553     ts.formatDiagnostic = formatDiagnostic;
99554     /** @internal */
99555     var ForegroundColorEscapeSequences;
99556     (function (ForegroundColorEscapeSequences) {
99557         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99558         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99559         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99560         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99561         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99562     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99563     var gutterStyleSequence = "\u001b[7m";
99564     var gutterSeparator = " ";
99565     var resetEscapeSequence = "\u001b[0m";
99566     var ellipsis = "...";
99567     var halfIndent = "  ";
99568     var indent = "    ";
99569     function getCategoryFormat(category) {
99570         switch (category) {
99571             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99572             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99573             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99574             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99575         }
99576     }
99577     /** @internal */
99578     function formatColorAndReset(text, formatStyle) {
99579         return formatStyle + text + resetEscapeSequence;
99580     }
99581     ts.formatColorAndReset = formatColorAndReset;
99582     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99583         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99584         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99585         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99586         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99587         var gutterWidth = (lastLine + 1 + "").length;
99588         if (hasMoreThanFiveLines) {
99589             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99590         }
99591         var context = "";
99592         for (var i = firstLine; i <= lastLine; i++) {
99593             context += host.getNewLine();
99594             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99595             // so we'll skip ahead to the second-to-last line.
99596             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99597                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99598                 i = lastLine - 1;
99599             }
99600             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99601             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99602             var lineContent = file.text.slice(lineStart, lineEnd);
99603             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99604             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99605             // Output the gutter and the actual contents of the line.
99606             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99607             context += lineContent + host.getNewLine();
99608             // Output the gutter and the error span for the line using tildes.
99609             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99610             context += squiggleColor;
99611             if (i === firstLine) {
99612                 // If we're on the last line, then limit it to the last character of the last line.
99613                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99614                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99615                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99616                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99617             }
99618             else if (i === lastLine) {
99619                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99620             }
99621             else {
99622                 // Squiggle the entire line.
99623                 context += lineContent.replace(/./g, "~");
99624             }
99625             context += resetEscapeSequence;
99626         }
99627         return context;
99628     }
99629     /* @internal */
99630     function formatLocation(file, start, host, color) {
99631         if (color === void 0) { color = formatColorAndReset; }
99632         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99633         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99634         var output = "";
99635         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99636         output += ":";
99637         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99638         output += ":";
99639         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99640         return output;
99641     }
99642     ts.formatLocation = formatLocation;
99643     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99644         var output = "";
99645         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99646             var diagnostic = diagnostics_3[_i];
99647             if (diagnostic.file) {
99648                 var file = diagnostic.file, start = diagnostic.start;
99649                 output += formatLocation(file, start, host); // TODO: GH#18217
99650                 output += " - ";
99651             }
99652             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99653             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99654             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99655             if (diagnostic.file) {
99656                 output += host.getNewLine();
99657                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99658                 if (diagnostic.relatedInformation) {
99659                     output += host.getNewLine();
99660                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99661                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99662                         if (file) {
99663                             output += host.getNewLine();
99664                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99665                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99666                         }
99667                         output += host.getNewLine();
99668                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99669                     }
99670                 }
99671             }
99672             output += host.getNewLine();
99673         }
99674         return output;
99675     }
99676     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99677     function flattenDiagnosticMessageText(diag, newLine, indent) {
99678         if (indent === void 0) { indent = 0; }
99679         if (ts.isString(diag)) {
99680             return diag;
99681         }
99682         else if (diag === undefined) {
99683             return "";
99684         }
99685         var result = "";
99686         if (indent) {
99687             result += newLine;
99688             for (var i = 0; i < indent; i++) {
99689                 result += "  ";
99690             }
99691         }
99692         result += diag.messageText;
99693         indent++;
99694         if (diag.next) {
99695             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99696                 var kid = _a[_i];
99697                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99698             }
99699         }
99700         return result;
99701     }
99702     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99703     /* @internal */
99704     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99705         if (names.length === 0) {
99706             return [];
99707         }
99708         var resolutions = [];
99709         var cache = ts.createMap();
99710         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99711             var name = names_2[_i];
99712             var result = void 0;
99713             if (cache.has(name)) {
99714                 result = cache.get(name);
99715             }
99716             else {
99717                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99718             }
99719             resolutions.push(result);
99720         }
99721         return resolutions;
99722     }
99723     ts.loadWithLocalCache = loadWithLocalCache;
99724     /* @internal */
99725     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99726     /**
99727      * Determines if program structure is upto date or needs to be recreated
99728      */
99729     /* @internal */
99730     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99731         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99732         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99733             return false;
99734         }
99735         // If root file names don't match
99736         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99737             return false;
99738         }
99739         var seenResolvedRefs;
99740         // If project references don't match
99741         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99742             return false;
99743         }
99744         // If any file is not up-to-date, then the whole program is not up-to-date
99745         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99746             return false;
99747         }
99748         // If any of the missing file paths are now created
99749         if (program.getMissingFilePaths().some(fileExists)) {
99750             return false;
99751         }
99752         var currentOptions = program.getCompilerOptions();
99753         // If the compilation settings do no match, then the program is not up-to-date
99754         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99755             return false;
99756         }
99757         // If everything matches but the text of config file is changed,
99758         // error locations can change for program options, so update the program
99759         if (currentOptions.configFile && newOptions.configFile) {
99760             return currentOptions.configFile.text === newOptions.configFile.text;
99761         }
99762         return true;
99763         function sourceFileNotUptoDate(sourceFile) {
99764             return !sourceFileVersionUptoDate(sourceFile) ||
99765                 hasInvalidatedResolution(sourceFile.path);
99766         }
99767         function sourceFileVersionUptoDate(sourceFile) {
99768             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99769         }
99770         function projectReferenceUptoDate(oldRef, newRef, index) {
99771             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99772                 return false;
99773             }
99774             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99775         }
99776         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99777             if (oldResolvedRef) {
99778                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99779                     // Assume true
99780                     return true;
99781                 }
99782                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99783                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99784                     return false;
99785                 }
99786                 // Add to seen before checking the referenced paths of this config file
99787                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99788                 // If child project references are upto date, this project reference is uptodate
99789                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99790                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99791                 });
99792             }
99793             // In old program, not able to resolve project reference path,
99794             // so if config file doesnt exist, it is uptodate.
99795             return !fileExists(resolveProjectReferencePath(oldRef));
99796         }
99797     }
99798     ts.isProgramUptoDate = isProgramUptoDate;
99799     function getConfigFileParsingDiagnostics(configFileParseResult) {
99800         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99801             configFileParseResult.errors;
99802     }
99803     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99804     /**
99805      * Determine if source file needs to be re-created even if its text hasn't changed
99806      */
99807     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99808         if (!program)
99809             return false;
99810         // If any compiler options change, we can't reuse old source file even if version match
99811         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
99812         var oldOptions = program.getCompilerOptions();
99813         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
99814             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
99815         });
99816     }
99817     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
99818         return {
99819             rootNames: rootNames,
99820             options: options,
99821             host: host,
99822             oldProgram: oldProgram,
99823             configFileParsingDiagnostics: configFileParsingDiagnostics
99824         };
99825     }
99826     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
99827         var _a;
99828         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
99829         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
99830         var oldProgram = createProgramOptions.oldProgram;
99831         var processingDefaultLibFiles;
99832         var processingOtherFiles;
99833         var files;
99834         var symlinks;
99835         var commonSourceDirectory;
99836         var diagnosticsProducingTypeChecker;
99837         var noDiagnosticsTypeChecker;
99838         var classifiableNames;
99839         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
99840         // Todo:: Use this to report why file was included in --extendedDiagnostics
99841         var refFileMap;
99842         var cachedBindAndCheckDiagnosticsForFile = {};
99843         var cachedDeclarationDiagnosticsForFile = {};
99844         var resolvedTypeReferenceDirectives = ts.createMap();
99845         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
99846         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
99847         // This works as imported modules are discovered recursively in a depth first manner, specifically:
99848         // - For each root file, findSourceFile is called.
99849         // - This calls processImportedModules for each module imported in the source file.
99850         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
99851         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
99852         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
99853         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
99854         var currentNodeModulesDepth = 0;
99855         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
99856         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
99857         var modulesWithElidedImports = ts.createMap();
99858         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
99859         var sourceFilesFoundSearchingNodeModules = ts.createMap();
99860         ts.performance.mark("beforeProgram");
99861         var host = createProgramOptions.host || createCompilerHost(options);
99862         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
99863         var skipDefaultLib = options.noLib;
99864         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
99865         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
99866         var programDiagnostics = ts.createDiagnosticCollection();
99867         var currentDirectory = host.getCurrentDirectory();
99868         var supportedExtensions = ts.getSupportedExtensions(options);
99869         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
99870         // Map storing if there is emit blocking diagnostics for given input
99871         var hasEmitBlockingDiagnostics = ts.createMap();
99872         var _compilerOptionsObjectLiteralSyntax;
99873         var moduleResolutionCache;
99874         var actualResolveModuleNamesWorker;
99875         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
99876         if (host.resolveModuleNames) {
99877             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
99878                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
99879                 if (!resolved || resolved.extension !== undefined) {
99880                     return resolved;
99881                 }
99882                 var withExtension = ts.clone(resolved);
99883                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
99884                 return withExtension;
99885             }); };
99886         }
99887         else {
99888             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
99889             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
99890             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
99891         }
99892         var actualResolveTypeReferenceDirectiveNamesWorker;
99893         if (host.resolveTypeReferenceDirectives) {
99894             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
99895         }
99896         else {
99897             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
99898             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
99899         }
99900         // Map from a stringified PackageId to the source file with that id.
99901         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
99902         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
99903         var packageIdToSourceFile = ts.createMap();
99904         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
99905         var sourceFileToPackageName = ts.createMap();
99906         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
99907         var redirectTargetsMap = ts.createMultiMap();
99908         /**
99909          * map with
99910          * - SourceFile if present
99911          * - false if sourceFile missing for source of project reference redirect
99912          * - undefined otherwise
99913          */
99914         var filesByName = ts.createMap();
99915         var missingFilePaths;
99916         // stores 'filename -> file association' ignoring case
99917         // used to track cases when two file names differ only in casing
99918         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
99919         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
99920         var resolvedProjectReferences;
99921         var projectReferenceRedirects;
99922         var mapFromFileToProjectReferenceRedirects;
99923         var mapFromToProjectReferenceRedirectSource;
99924         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
99925             !options.disableSourceOfProjectReferenceRedirect;
99926         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
99927             compilerHost: host,
99928             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
99929             toPath: toPath,
99930             getResolvedProjectReferences: getResolvedProjectReferences,
99931             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
99932             forEachResolvedProjectReference: forEachResolvedProjectReference
99933         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
99934         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
99935         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
99936         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
99937         var structuralIsReused;
99938         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
99939         if (structuralIsReused !== 2 /* Completely */) {
99940             processingDefaultLibFiles = [];
99941             processingOtherFiles = [];
99942             if (projectReferences) {
99943                 if (!resolvedProjectReferences) {
99944                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
99945                 }
99946                 if (rootNames.length) {
99947                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
99948                         var parsedRef = resolvedProjectReferences_1[_i];
99949                         if (!parsedRef)
99950                             continue;
99951                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
99952                         if (useSourceOfProjectReferenceRedirect) {
99953                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99954                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
99955                                     var fileName = _d[_c];
99956                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99957                                 }
99958                             }
99959                         }
99960                         else {
99961                             if (out) {
99962                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99963                             }
99964                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99965                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
99966                                     var fileName = _f[_e];
99967                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
99968                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99969                                     }
99970                                 }
99971                             }
99972                         }
99973                     }
99974                 }
99975             }
99976             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
99977             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
99978             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
99979             if (typeReferences.length) {
99980                 // This containingFilename needs to match with the one used in managed-side
99981                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
99982                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
99983                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
99984                 for (var i = 0; i < typeReferences.length; i++) {
99985                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
99986                 }
99987             }
99988             // Do not process the default library if:
99989             //  - The '--noLib' flag is used.
99990             //  - A 'no-default-lib' reference comment is encountered in
99991             //      processing the root files.
99992             if (rootNames.length && !skipDefaultLib) {
99993                 // If '--lib' is not specified, include default library file according to '--target'
99994                 // otherwise, using options specified in '--lib' instead of '--target' default library file
99995                 var defaultLibraryFileName = getDefaultLibraryFileName();
99996                 if (!options.lib && defaultLibraryFileName) {
99997                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
99998                 }
99999                 else {
100000                     ts.forEach(options.lib, function (libFileName) {
100001                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100002                     });
100003                 }
100004             }
100005             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100006                 var path = _a[0], file = _a[1];
100007                 return file === undefined ? path : undefined;
100008             }));
100009             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100010             processingDefaultLibFiles = undefined;
100011             processingOtherFiles = undefined;
100012         }
100013         ts.Debug.assert(!!missingFilePaths);
100014         // Release any files we have acquired in the old program but are
100015         // not part of the new program.
100016         if (oldProgram && host.onReleaseOldSourceFile) {
100017             var oldSourceFiles = oldProgram.getSourceFiles();
100018             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100019                 var oldSourceFile = oldSourceFiles_1[_g];
100020                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100021                 if (shouldCreateNewSourceFile || !newFile ||
100022                     // old file wasnt redirect but new file is
100023                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100024                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100025                 }
100026             }
100027             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100028                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100029                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100030                 }
100031             });
100032         }
100033         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100034         oldProgram = undefined;
100035         var program = {
100036             getRootFileNames: function () { return rootNames; },
100037             getSourceFile: getSourceFile,
100038             getSourceFileByPath: getSourceFileByPath,
100039             getSourceFiles: function () { return files; },
100040             getMissingFilePaths: function () { return missingFilePaths; },
100041             getRefFileMap: function () { return refFileMap; },
100042             getFilesByNameMap: function () { return filesByName; },
100043             getCompilerOptions: function () { return options; },
100044             getSyntacticDiagnostics: getSyntacticDiagnostics,
100045             getOptionsDiagnostics: getOptionsDiagnostics,
100046             getGlobalDiagnostics: getGlobalDiagnostics,
100047             getSemanticDiagnostics: getSemanticDiagnostics,
100048             getSuggestionDiagnostics: getSuggestionDiagnostics,
100049             getDeclarationDiagnostics: getDeclarationDiagnostics,
100050             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100051             getProgramDiagnostics: getProgramDiagnostics,
100052             getTypeChecker: getTypeChecker,
100053             getClassifiableNames: getClassifiableNames,
100054             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100055             getCommonSourceDirectory: getCommonSourceDirectory,
100056             emit: emit,
100057             getCurrentDirectory: function () { return currentDirectory; },
100058             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100059             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100060             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100061             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100062             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100063             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100064             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100065             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100066             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100067             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100068             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100069             getSourceFileFromReference: getSourceFileFromReference,
100070             getLibFileFromReference: getLibFileFromReference,
100071             sourceFileToPackageName: sourceFileToPackageName,
100072             redirectTargetsMap: redirectTargetsMap,
100073             isEmittedFile: isEmittedFile,
100074             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100075             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100076             getProjectReferences: getProjectReferences,
100077             getResolvedProjectReferences: getResolvedProjectReferences,
100078             getProjectReferenceRedirect: getProjectReferenceRedirect,
100079             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100080             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100081             forEachResolvedProjectReference: forEachResolvedProjectReference,
100082             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100083             emitBuildInfo: emitBuildInfo,
100084             fileExists: fileExists,
100085             getProbableSymlinks: getProbableSymlinks,
100086             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100087         };
100088         onProgramCreateComplete();
100089         verifyCompilerOptions();
100090         ts.performance.mark("afterProgram");
100091         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100092         return program;
100093         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100094             ts.performance.mark("beforeResolveModule");
100095             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100096             ts.performance.mark("afterResolveModule");
100097             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100098             return result;
100099         }
100100         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100101             ts.performance.mark("beforeResolveTypeReference");
100102             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100103             ts.performance.mark("afterResolveTypeReference");
100104             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100105             return result;
100106         }
100107         function compareDefaultLibFiles(a, b) {
100108             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100109         }
100110         function getDefaultLibFilePriority(a) {
100111             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100112                 var basename = ts.getBaseFileName(a.fileName);
100113                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100114                     return 0;
100115                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100116                 var index = ts.libs.indexOf(name);
100117                 if (index !== -1)
100118                     return index + 1;
100119             }
100120             return ts.libs.length + 2;
100121         }
100122         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100123             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100124         }
100125         function toPath(fileName) {
100126             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100127         }
100128         function getCommonSourceDirectory() {
100129             if (commonSourceDirectory === undefined) {
100130                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100131                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100132                     // If a rootDir is specified use it as the commonSourceDirectory
100133                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100134                 }
100135                 else if (options.composite && options.configFilePath) {
100136                     // Project compilations never infer their root from the input source paths
100137                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100138                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100139                 }
100140                 else {
100141                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100142                 }
100143                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100144                     // Make sure directory path ends with directory separator so this string can directly
100145                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100146                     // start with / making it rooted path
100147                     commonSourceDirectory += ts.directorySeparator;
100148                 }
100149             }
100150             return commonSourceDirectory;
100151         }
100152         function getClassifiableNames() {
100153             if (!classifiableNames) {
100154                 // Initialize a checker so that all our files are bound.
100155                 getTypeChecker();
100156                 classifiableNames = ts.createUnderscoreEscapedMap();
100157                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100158                     var sourceFile = files_2[_i];
100159                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100160                 }
100161             }
100162             return classifiableNames;
100163         }
100164         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100165             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100166                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100167                 // the best we can do is fallback to the default logic.
100168                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100169             }
100170             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100171             if (oldSourceFile !== file && file.resolvedModules) {
100172                 // `file` was created for the new program.
100173                 //
100174                 // We only set `file.resolvedModules` via work from the current function,
100175                 // so it is defined iff we already called the current function on `file`.
100176                 // That call happened no later than the creation of the `file` object,
100177                 // which per above occurred during the current program creation.
100178                 // Since we assume the filesystem does not change during program creation,
100179                 // it is safe to reuse resolutions from the earlier call.
100180                 var result_11 = [];
100181                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100182                     var moduleName = moduleNames_1[_i];
100183                     var resolvedModule = file.resolvedModules.get(moduleName);
100184                     result_11.push(resolvedModule);
100185                 }
100186                 return result_11;
100187             }
100188             // At this point, we know at least one of the following hold:
100189             // - file has local declarations for ambient modules
100190             // - old program state is available
100191             // With this information, we can infer some module resolutions without performing resolution.
100192             /** An ordered list of module names for which we cannot recover the resolution. */
100193             var unknownModuleNames;
100194             /**
100195              * The indexing of elements in this list matches that of `moduleNames`.
100196              *
100197              * Before combining results, result[i] is in one of the following states:
100198              * * undefined: needs to be recomputed,
100199              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100200              * Needs to be reset to undefined before returning,
100201              * * ResolvedModuleFull instance: can be reused.
100202              */
100203             var result;
100204             var reusedNames;
100205             /** A transient placeholder used to mark predicted resolution in the result list. */
100206             var predictedToResolveToAmbientModuleMarker = {};
100207             for (var i = 0; i < moduleNames.length; i++) {
100208                 var moduleName = moduleNames[i];
100209                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100210                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100211                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100212                     if (oldResolvedModule) {
100213                         if (ts.isTraceEnabled(options, host)) {
100214                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100215                         }
100216                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100217                         (reusedNames || (reusedNames = [])).push(moduleName);
100218                         continue;
100219                     }
100220                 }
100221                 // We know moduleName resolves to an ambient module provided that moduleName:
100222                 // - is in the list of ambient modules locally declared in the current source file.
100223                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100224                 //   (so the same module declaration will land in the new program)
100225                 var resolvesToAmbientModuleInNonModifiedFile = false;
100226                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100227                     resolvesToAmbientModuleInNonModifiedFile = true;
100228                     if (ts.isTraceEnabled(options, host)) {
100229                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100230                     }
100231                 }
100232                 else {
100233                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100234                 }
100235                 if (resolvesToAmbientModuleInNonModifiedFile) {
100236                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100237                 }
100238                 else {
100239                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100240                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100241                 }
100242             }
100243             var resolutions = unknownModuleNames && unknownModuleNames.length
100244                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100245                 : ts.emptyArray;
100246             // Combine results of resolutions and predicted results
100247             if (!result) {
100248                 // There were no unresolved/ambient resolutions.
100249                 ts.Debug.assert(resolutions.length === moduleNames.length);
100250                 return resolutions;
100251             }
100252             var j = 0;
100253             for (var i = 0; i < result.length; i++) {
100254                 if (result[i]) {
100255                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100256                     // If it is the former, we can leave it as is.
100257                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100258                         result[i] = undefined; // TODO: GH#18217
100259                     }
100260                 }
100261                 else {
100262                     result[i] = resolutions[j];
100263                     j++;
100264                 }
100265             }
100266             ts.Debug.assert(j === resolutions.length);
100267             return result;
100268             // If we change our policy of rechecking failed lookups on each program create,
100269             // we should adjust the value returned here.
100270             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100271                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100272                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100273                 if (resolutionToFile && resolvedFile) {
100274                     // In the old program, we resolved to an ambient module that was in the same
100275                     //   place as we expected to find an actual module file.
100276                     // We actually need to return 'false' here even though this seems like a 'true' case
100277                     //   because the normal module resolution algorithm will find this anyway.
100278                     return false;
100279                 }
100280                 // at least one of declarations should come from non-modified source file
100281                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100282                 if (!unmodifiedFile) {
100283                     return false;
100284                 }
100285                 if (ts.isTraceEnabled(options, host)) {
100286                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100287                 }
100288                 return true;
100289             }
100290         }
100291         function canReuseProjectReferences() {
100292             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100293                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100294                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100295                 if (oldResolvedRef) {
100296                     // Resolved project reference has gone missing or changed
100297                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100298                 }
100299                 else {
100300                     // A previously-unresolved reference may be resolved now
100301                     return newResolvedRef !== undefined;
100302                 }
100303             }, function (oldProjectReferences, parent) {
100304                 // If array of references is changed, we cant resue old program
100305                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100306                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100307             });
100308         }
100309         function tryReuseStructureFromOldProgram() {
100310             if (!oldProgram) {
100311                 return 0 /* Not */;
100312             }
100313             // check properties that can affect structure of the program or module resolution strategy
100314             // if any of these properties has changed - structure cannot be reused
100315             var oldOptions = oldProgram.getCompilerOptions();
100316             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100317                 return oldProgram.structureIsReused = 0 /* Not */;
100318             }
100319             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100320             // there is an old program, check if we can reuse its structure
100321             var oldRootNames = oldProgram.getRootFileNames();
100322             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100323                 return oldProgram.structureIsReused = 0 /* Not */;
100324             }
100325             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100326                 return oldProgram.structureIsReused = 0 /* Not */;
100327             }
100328             // Check if any referenced project tsconfig files are different
100329             if (!canReuseProjectReferences()) {
100330                 return oldProgram.structureIsReused = 0 /* Not */;
100331             }
100332             if (projectReferences) {
100333                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100334             }
100335             // check if program source files has changed in the way that can affect structure of the program
100336             var newSourceFiles = [];
100337             var modifiedSourceFiles = [];
100338             oldProgram.structureIsReused = 2 /* Completely */;
100339             // If the missing file paths are now present, it can change the progam structure,
100340             // and hence cant reuse the structure.
100341             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100342             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100343                 return oldProgram.structureIsReused = 0 /* Not */;
100344             }
100345             var oldSourceFiles = oldProgram.getSourceFiles();
100346             var SeenPackageName;
100347             (function (SeenPackageName) {
100348                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100349                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100350             })(SeenPackageName || (SeenPackageName = {}));
100351             var seenPackageNames = ts.createMap();
100352             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100353                 var oldSourceFile = oldSourceFiles_2[_i];
100354                 var newSourceFile = host.getSourceFileByPath
100355                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100356                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100357                 if (!newSourceFile) {
100358                     return oldProgram.structureIsReused = 0 /* Not */;
100359                 }
100360                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100361                 var fileChanged = void 0;
100362                 if (oldSourceFile.redirectInfo) {
100363                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100364                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100365                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100366                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100367                         return oldProgram.structureIsReused = 0 /* Not */;
100368                     }
100369                     fileChanged = false;
100370                     newSourceFile = oldSourceFile; // Use the redirect.
100371                 }
100372                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100373                     // If a redirected-to source file changes, the redirect may be broken.
100374                     if (newSourceFile !== oldSourceFile) {
100375                         return oldProgram.structureIsReused = 0 /* Not */;
100376                     }
100377                     fileChanged = false;
100378                 }
100379                 else {
100380                     fileChanged = newSourceFile !== oldSourceFile;
100381                 }
100382                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100383                 newSourceFile.path = oldSourceFile.path;
100384                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100385                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100386                 newSourceFile.fileName = oldSourceFile.fileName;
100387                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100388                 if (packageName !== undefined) {
100389                     // If there are 2 different source files for the same package name and at least one of them changes,
100390                     // they might become redirects. So we must rebuild the program.
100391                     var prevKind = seenPackageNames.get(packageName);
100392                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100393                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100394                         return oldProgram.structureIsReused = 0 /* Not */;
100395                     }
100396                     seenPackageNames.set(packageName, newKind);
100397                 }
100398                 if (fileChanged) {
100399                     // The `newSourceFile` object was created for the new program.
100400                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100401                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100402                         return oldProgram.structureIsReused = 0 /* Not */;
100403                     }
100404                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100405                         // value of no-default-lib has changed
100406                         // this will affect if default library is injected into the list of files
100407                         oldProgram.structureIsReused = 1 /* SafeModules */;
100408                     }
100409                     // check tripleslash references
100410                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100411                         // tripleslash references has changed
100412                         oldProgram.structureIsReused = 1 /* SafeModules */;
100413                     }
100414                     // check imports and module augmentations
100415                     collectExternalModuleReferences(newSourceFile);
100416                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100417                         // imports has changed
100418                         oldProgram.structureIsReused = 1 /* SafeModules */;
100419                     }
100420                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100421                         // moduleAugmentations has changed
100422                         oldProgram.structureIsReused = 1 /* SafeModules */;
100423                     }
100424                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100425                         // dynamicImport has changed
100426                         oldProgram.structureIsReused = 1 /* SafeModules */;
100427                     }
100428                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100429                         // 'types' references has changed
100430                         oldProgram.structureIsReused = 1 /* SafeModules */;
100431                     }
100432                     // tentatively approve the file
100433                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100434                 }
100435                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100436                     // 'module/types' references could have changed
100437                     oldProgram.structureIsReused = 1 /* SafeModules */;
100438                     // add file to the modified list so that we will resolve it later
100439                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100440                 }
100441                 // if file has passed all checks it should be safe to reuse it
100442                 newSourceFiles.push(newSourceFile);
100443             }
100444             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100445                 return oldProgram.structureIsReused;
100446             }
100447             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100448             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100449                 var oldFile = oldSourceFiles_3[_a];
100450                 if (!ts.contains(modifiedFiles, oldFile)) {
100451                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100452                         var moduleName = _c[_b];
100453                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100454                     }
100455                 }
100456             }
100457             // try to verify results of module resolution
100458             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100459                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100460                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100461                 var moduleNames = getModuleNames(newSourceFile);
100462                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100463                 // ensure that module resolution results are still correct
100464                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100465                 if (resolutionsChanged) {
100466                     oldProgram.structureIsReused = 1 /* SafeModules */;
100467                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100468                 }
100469                 else {
100470                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100471                 }
100472                 if (resolveTypeReferenceDirectiveNamesWorker) {
100473                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100474                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100475                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100476                     // ensure that types resolutions are still correct
100477                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100478                     if (resolutionsChanged_1) {
100479                         oldProgram.structureIsReused = 1 /* SafeModules */;
100480                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100481                     }
100482                     else {
100483                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100484                     }
100485                 }
100486             }
100487             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100488                 return oldProgram.structureIsReused;
100489             }
100490             if (host.hasChangedAutomaticTypeDirectiveNames) {
100491                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100492             }
100493             missingFilePaths = oldProgram.getMissingFilePaths();
100494             refFileMap = oldProgram.getRefFileMap();
100495             // update fileName -> file mapping
100496             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100497             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100498                 var newSourceFile = newSourceFiles_1[_f];
100499                 filesByName.set(newSourceFile.path, newSourceFile);
100500             }
100501             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100502             oldFilesByNameMap.forEach(function (oldFile, path) {
100503                 if (!oldFile) {
100504                     filesByName.set(path, oldFile);
100505                     return;
100506                 }
100507                 if (oldFile.path === path) {
100508                     // Set the file as found during node modules search if it was found that way in old progra,
100509                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100510                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100511                     }
100512                     return;
100513                 }
100514                 filesByName.set(path, filesByName.get(oldFile.path));
100515             });
100516             files = newSourceFiles;
100517             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100518             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100519                 var modifiedFile = modifiedSourceFiles_2[_g];
100520                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100521             }
100522             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100523             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100524             redirectTargetsMap = oldProgram.redirectTargetsMap;
100525             return oldProgram.structureIsReused = 2 /* Completely */;
100526         }
100527         function getEmitHost(writeFileCallback) {
100528             return {
100529                 getPrependNodes: getPrependNodes,
100530                 getCanonicalFileName: getCanonicalFileName,
100531                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100532                 getCompilerOptions: program.getCompilerOptions,
100533                 getCurrentDirectory: function () { return currentDirectory; },
100534                 getNewLine: function () { return host.getNewLine(); },
100535                 getSourceFile: program.getSourceFile,
100536                 getSourceFileByPath: program.getSourceFileByPath,
100537                 getSourceFiles: program.getSourceFiles,
100538                 getLibFileFromReference: program.getLibFileFromReference,
100539                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100540                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100541                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100542                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100543                 getProbableSymlinks: getProbableSymlinks,
100544                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100545                 isEmitBlocked: isEmitBlocked,
100546                 readFile: function (f) { return host.readFile(f); },
100547                 fileExists: function (f) {
100548                     // Use local caches
100549                     var path = toPath(f);
100550                     if (getSourceFileByPath(path))
100551                         return true;
100552                     if (ts.contains(missingFilePaths, path))
100553                         return false;
100554                     // Before falling back to the host
100555                     return host.fileExists(f);
100556                 },
100557                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100558                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100559                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100560                 redirectTargetsMap: redirectTargetsMap,
100561             };
100562         }
100563         function emitBuildInfo(writeFileCallback) {
100564             ts.Debug.assert(!options.out && !options.outFile);
100565             ts.performance.mark("beforeEmit");
100566             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100567             /*targetSourceFile*/ undefined, 
100568             /*transformers*/ ts.noTransformers, 
100569             /*emitOnlyDtsFiles*/ false, 
100570             /*onlyBuildInfo*/ true);
100571             ts.performance.mark("afterEmit");
100572             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100573             return emitResult;
100574         }
100575         function getResolvedProjectReferences() {
100576             return resolvedProjectReferences;
100577         }
100578         function getProjectReferences() {
100579             return projectReferences;
100580         }
100581         function getPrependNodes() {
100582             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100583                 var path = toPath(fileName);
100584                 var sourceFile = getSourceFileByPath(path);
100585                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100586             });
100587         }
100588         function isSourceFileFromExternalLibrary(file) {
100589             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100590         }
100591         function isSourceFileDefaultLibrary(file) {
100592             if (file.hasNoDefaultLib) {
100593                 return true;
100594             }
100595             if (!options.noLib) {
100596                 return false;
100597             }
100598             // If '--lib' is not specified, include default library file according to '--target'
100599             // otherwise, using options specified in '--lib' instead of '--target' default library file
100600             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100601             if (!options.lib) {
100602                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100603             }
100604             else {
100605                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100606             }
100607         }
100608         function getDiagnosticsProducingTypeChecker() {
100609             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100610         }
100611         function dropDiagnosticsProducingTypeChecker() {
100612             diagnosticsProducingTypeChecker = undefined;
100613         }
100614         function getTypeChecker() {
100615             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100616         }
100617         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100618             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100619         }
100620         function isEmitBlocked(emitFileName) {
100621             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100622         }
100623         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100624             if (!forceDtsEmit) {
100625                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100626                 if (result)
100627                     return result;
100628             }
100629             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100630             // any cost associated with it (like type checking) are appropriate associated with
100631             // the type-checking counter.
100632             //
100633             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100634             // This is because in the -out scenario all files need to be emitted, and therefore all
100635             // files need to be type checked. And the way to specify that all files need to be type
100636             // checked is to not pass the file to getEmitResolver.
100637             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100638             ts.performance.mark("beforeEmit");
100639             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100640             /*onlyBuildInfo*/ false, forceDtsEmit);
100641             ts.performance.mark("afterEmit");
100642             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100643             return emitResult;
100644         }
100645         function getSourceFile(fileName) {
100646             return getSourceFileByPath(toPath(fileName));
100647         }
100648         function getSourceFileByPath(path) {
100649             return filesByName.get(path) || undefined;
100650         }
100651         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100652             if (sourceFile) {
100653                 return getDiagnostics(sourceFile, cancellationToken);
100654             }
100655             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100656                 if (cancellationToken) {
100657                     cancellationToken.throwIfCancellationRequested();
100658                 }
100659                 return getDiagnostics(sourceFile, cancellationToken);
100660             }));
100661         }
100662         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100663             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100664         }
100665         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100666             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100667         }
100668         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100669             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100670         }
100671         function getProgramDiagnostics(sourceFile) {
100672             if (ts.skipTypeChecking(sourceFile, options, program)) {
100673                 return ts.emptyArray;
100674             }
100675             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100676             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100677             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100678         }
100679         function getMergedProgramDiagnostics(sourceFile) {
100680             var _a;
100681             var allDiagnostics = [];
100682             for (var _i = 1; _i < arguments.length; _i++) {
100683                 allDiagnostics[_i - 1] = arguments[_i];
100684             }
100685             var flatDiagnostics = ts.flatten(allDiagnostics);
100686             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100687                 return flatDiagnostics;
100688             }
100689             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100690         }
100691         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100692             var options = program.getCompilerOptions();
100693             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100694             if (!sourceFile || options.out || options.outFile) {
100695                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100696             }
100697             else {
100698                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100699             }
100700         }
100701         function getSyntacticDiagnosticsForFile(sourceFile) {
100702             // For JavaScript files, we report semantic errors for using TypeScript-only
100703             // constructs from within a JavaScript file as syntactic errors.
100704             if (ts.isSourceFileJS(sourceFile)) {
100705                 if (!sourceFile.additionalSyntacticDiagnostics) {
100706                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100707                 }
100708                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100709             }
100710             return sourceFile.parseDiagnostics;
100711         }
100712         function runWithCancellationToken(func) {
100713             try {
100714                 return func();
100715             }
100716             catch (e) {
100717                 if (e instanceof ts.OperationCanceledException) {
100718                     // We were canceled while performing the operation.  Because our type checker
100719                     // might be a bad state, we need to throw it away.
100720                     //
100721                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100722                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100723                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100724                     // cancel when the user has made a change anyways.  And, in that case, we (the
100725                     // program instance) will get thrown away anyways.  So trying to keep one of
100726                     // these type checkers alive doesn't serve much purpose.
100727                     noDiagnosticsTypeChecker = undefined;
100728                     diagnosticsProducingTypeChecker = undefined;
100729                 }
100730                 throw e;
100731             }
100732         }
100733         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100734             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100735         }
100736         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100737             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100738         }
100739         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100740             return runWithCancellationToken(function () {
100741                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100742                     return ts.emptyArray;
100743                 }
100744                 var typeChecker = getDiagnosticsProducingTypeChecker();
100745                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100746                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100747                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100748                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100749                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100750                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100751                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100752                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100753                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100754             });
100755         }
100756         function getMergedBindAndCheckDiagnostics(sourceFile) {
100757             var _a;
100758             var allDiagnostics = [];
100759             for (var _i = 1; _i < arguments.length; _i++) {
100760                 allDiagnostics[_i - 1] = arguments[_i];
100761             }
100762             var flatDiagnostics = ts.flatten(allDiagnostics);
100763             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100764                 return flatDiagnostics;
100765             }
100766             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100767             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100768                 var errorExpectation = _d[_c];
100769                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100770             }
100771             return diagnostics;
100772         }
100773         /**
100774          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100775          * Comments that match to any of those diagnostics are marked as used.
100776          */
100777         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100778             // Diagnostics are only reported if there is no comment directive preceding them
100779             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100780             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100781             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100782             return { diagnostics: diagnostics, directives: directives };
100783         }
100784         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100785             return runWithCancellationToken(function () {
100786                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100787             });
100788         }
100789         /**
100790          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100791          */
100792         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100793             var file = diagnostic.file, start = diagnostic.start;
100794             if (!file) {
100795                 return -1;
100796             }
100797             // Start out with the line just before the text
100798             var lineStarts = ts.getLineStarts(file);
100799             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100800             while (line >= 0) {
100801                 // As soon as that line is known to have a comment directive, use that
100802                 if (directives.markUsed(line)) {
100803                     return line;
100804                 }
100805                 // Stop searching if the line is not empty and not a comment
100806                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100807                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100808                     return -1;
100809                 }
100810                 line--;
100811             }
100812             return -1;
100813         }
100814         function getJSSyntacticDiagnosticsForFile(sourceFile) {
100815             return runWithCancellationToken(function () {
100816                 var diagnostics = [];
100817                 walk(sourceFile, sourceFile);
100818                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
100819                 return diagnostics;
100820                 function walk(node, parent) {
100821                     // Return directly from the case if the given node doesnt want to visit each child
100822                     // Otherwise break to visit each child
100823                     switch (parent.kind) {
100824                         case 156 /* Parameter */:
100825                         case 159 /* PropertyDeclaration */:
100826                         case 161 /* MethodDeclaration */:
100827                             if (parent.questionToken === node) {
100828                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
100829                                 return "skip";
100830                             }
100831                         // falls through
100832                         case 160 /* MethodSignature */:
100833                         case 162 /* Constructor */:
100834                         case 163 /* GetAccessor */:
100835                         case 164 /* SetAccessor */:
100836                         case 201 /* FunctionExpression */:
100837                         case 244 /* FunctionDeclaration */:
100838                         case 202 /* ArrowFunction */:
100839                         case 242 /* VariableDeclaration */:
100840                             // type annotation
100841                             if (parent.type === node) {
100842                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
100843                                 return "skip";
100844                             }
100845                     }
100846                     switch (node.kind) {
100847                         case 255 /* ImportClause */:
100848                             if (node.isTypeOnly) {
100849                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
100850                                 return "skip";
100851                             }
100852                             break;
100853                         case 260 /* ExportDeclaration */:
100854                             if (node.isTypeOnly) {
100855                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
100856                                 return "skip";
100857                             }
100858                             break;
100859                         case 253 /* ImportEqualsDeclaration */:
100860                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
100861                             return "skip";
100862                         case 259 /* ExportAssignment */:
100863                             if (node.isExportEquals) {
100864                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
100865                                 return "skip";
100866                             }
100867                             break;
100868                         case 279 /* HeritageClause */:
100869                             var heritageClause = node;
100870                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
100871                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
100872                                 return "skip";
100873                             }
100874                             break;
100875                         case 246 /* InterfaceDeclaration */:
100876                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
100877                             ts.Debug.assertIsDefined(interfaceKeyword);
100878                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
100879                             return "skip";
100880                         case 249 /* ModuleDeclaration */:
100881                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
100882                             ts.Debug.assertIsDefined(moduleKeyword);
100883                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
100884                             return "skip";
100885                         case 247 /* TypeAliasDeclaration */:
100886                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
100887                             return "skip";
100888                         case 248 /* EnumDeclaration */:
100889                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
100890                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
100891                             return "skip";
100892                         case 218 /* NonNullExpression */:
100893                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
100894                             return "skip";
100895                         case 217 /* AsExpression */:
100896                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
100897                             return "skip";
100898                         case 199 /* TypeAssertionExpression */:
100899                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
100900                     }
100901                 }
100902                 function walkArray(nodes, parent) {
100903                     if (parent.decorators === nodes && !options.experimentalDecorators) {
100904                         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));
100905                     }
100906                     switch (parent.kind) {
100907                         case 245 /* ClassDeclaration */:
100908                         case 214 /* ClassExpression */:
100909                         case 161 /* MethodDeclaration */:
100910                         case 162 /* Constructor */:
100911                         case 163 /* GetAccessor */:
100912                         case 164 /* SetAccessor */:
100913                         case 201 /* FunctionExpression */:
100914                         case 244 /* FunctionDeclaration */:
100915                         case 202 /* ArrowFunction */:
100916                             // Check type parameters
100917                             if (nodes === parent.typeParameters) {
100918                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
100919                                 return "skip";
100920                             }
100921                         // falls through
100922                         case 225 /* VariableStatement */:
100923                             // Check modifiers
100924                             if (nodes === parent.modifiers) {
100925                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
100926                                 return "skip";
100927                             }
100928                             break;
100929                         case 159 /* PropertyDeclaration */:
100930                             // Check modifiers of property declaration
100931                             if (nodes === parent.modifiers) {
100932                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
100933                                     var modifier = _a[_i];
100934                                     if (modifier.kind !== 120 /* StaticKeyword */) {
100935                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100936                                     }
100937                                 }
100938                                 return "skip";
100939                             }
100940                             break;
100941                         case 156 /* Parameter */:
100942                             // Check modifiers of parameter declaration
100943                             if (nodes === parent.modifiers) {
100944                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
100945                                 return "skip";
100946                             }
100947                             break;
100948                         case 196 /* CallExpression */:
100949                         case 197 /* NewExpression */:
100950                         case 216 /* ExpressionWithTypeArguments */:
100951                         case 267 /* JsxSelfClosingElement */:
100952                         case 268 /* JsxOpeningElement */:
100953                         case 198 /* TaggedTemplateExpression */:
100954                             // Check type arguments
100955                             if (nodes === parent.typeArguments) {
100956                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
100957                                 return "skip";
100958                             }
100959                             break;
100960                     }
100961                 }
100962                 function checkModifiers(modifiers, isConstValid) {
100963                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
100964                         var modifier = modifiers_1[_i];
100965                         switch (modifier.kind) {
100966                             case 81 /* ConstKeyword */:
100967                                 if (isConstValid) {
100968                                     continue;
100969                                 }
100970                             // to report error,
100971                             // falls through
100972                             case 119 /* PublicKeyword */:
100973                             case 117 /* PrivateKeyword */:
100974                             case 118 /* ProtectedKeyword */:
100975                             case 138 /* ReadonlyKeyword */:
100976                             case 130 /* DeclareKeyword */:
100977                             case 122 /* AbstractKeyword */:
100978                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100979                                 break;
100980                             // These are all legal modifiers.
100981                             case 120 /* StaticKeyword */:
100982                             case 89 /* ExportKeyword */:
100983                             case 84 /* DefaultKeyword */:
100984                         }
100985                     }
100986                 }
100987                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
100988                     var start = nodes.pos;
100989                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
100990                 }
100991                 // Since these are syntactic diagnostics, parent might not have been set
100992                 // this means the sourceFile cannot be infered from the node
100993                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
100994                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
100995                 }
100996             });
100997         }
100998         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
100999             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101000         }
101001         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101002             return runWithCancellationToken(function () {
101003                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101004                 // Don't actually write any files since we're just getting diagnostics.
101005                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101006             });
101007         }
101008         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101009             var cachedResult = sourceFile
101010                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101011                 : cache.allDiagnostics;
101012             if (cachedResult) {
101013                 return cachedResult;
101014             }
101015             var result = getDiagnostics(sourceFile, cancellationToken);
101016             if (sourceFile) {
101017                 if (!cache.perFile) {
101018                     cache.perFile = ts.createMap();
101019                 }
101020                 cache.perFile.set(sourceFile.path, result);
101021             }
101022             else {
101023                 cache.allDiagnostics = result;
101024             }
101025             return result;
101026         }
101027         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101028             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101029         }
101030         function getOptionsDiagnostics() {
101031             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101032         }
101033         function getOptionsDiagnosticsOfConfigFile() {
101034             if (!options.configFile) {
101035                 return ts.emptyArray;
101036             }
101037             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101038             forEachResolvedProjectReference(function (resolvedRef) {
101039                 if (resolvedRef) {
101040                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101041                 }
101042             });
101043             return diagnostics;
101044         }
101045         function getGlobalDiagnostics() {
101046             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101047         }
101048         function getConfigFileParsingDiagnostics() {
101049             return configFileParsingDiagnostics || ts.emptyArray;
101050         }
101051         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101052             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101053         }
101054         function fileReferenceIsEqualTo(a, b) {
101055             return a.fileName === b.fileName;
101056         }
101057         function moduleNameIsEqualTo(a, b) {
101058             return a.kind === 75 /* Identifier */
101059                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101060                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101061         }
101062         function collectExternalModuleReferences(file) {
101063             if (file.imports) {
101064                 return;
101065             }
101066             var isJavaScriptFile = ts.isSourceFileJS(file);
101067             var isExternalModuleFile = ts.isExternalModule(file);
101068             // file.imports may not be undefined if there exists dynamic import
101069             var imports;
101070             var moduleAugmentations;
101071             var ambientModules;
101072             // If we are importing helpers, we need to add a synthetic reference to resolve the
101073             // helpers library.
101074             if (options.importHelpers
101075                 && (options.isolatedModules || isExternalModuleFile)
101076                 && !file.isDeclarationFile) {
101077                 // synthesize 'import "tslib"' declaration
101078                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101079                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101080                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101081                 externalHelpersModuleReference.parent = importDecl;
101082                 importDecl.parent = file;
101083                 imports = [externalHelpersModuleReference];
101084             }
101085             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101086                 var node = _a[_i];
101087                 collectModuleReferences(node, /*inAmbientModule*/ false);
101088             }
101089             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101090                 collectDynamicImportOrRequireCalls(file);
101091             }
101092             file.imports = imports || ts.emptyArray;
101093             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101094             file.ambientModuleNames = ambientModules || ts.emptyArray;
101095             return;
101096             function collectModuleReferences(node, inAmbientModule) {
101097                 if (ts.isAnyImportOrReExport(node)) {
101098                     var moduleNameExpr = ts.getExternalModuleName(node);
101099                     // TypeScript 1.0 spec (April 2014): 12.1.6
101100                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101101                     // only through top - level external module names. Relative external module names are not permitted.
101102                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101103                         imports = ts.append(imports, moduleNameExpr);
101104                     }
101105                 }
101106                 else if (ts.isModuleDeclaration(node)) {
101107                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101108                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101109                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101110                         // This will happen in two cases:
101111                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101112                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101113                         //   immediately nested in top level ambient module declaration .
101114                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101115                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101116                         }
101117                         else if (!inAmbientModule) {
101118                             if (file.isDeclarationFile) {
101119                                 // for global .d.ts files record name of ambient module
101120                                 (ambientModules || (ambientModules = [])).push(nameText);
101121                             }
101122                             // An AmbientExternalModuleDeclaration declares an external module.
101123                             // This type of declaration is permitted only in the global module.
101124                             // The StringLiteral must specify a top - level external module name.
101125                             // Relative external module names are not permitted
101126                             // NOTE: body of ambient module is always a module block, if it exists
101127                             var body = node.body;
101128                             if (body) {
101129                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101130                                     var statement = _a[_i];
101131                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101132                                 }
101133                             }
101134                         }
101135                     }
101136                 }
101137             }
101138             function collectDynamicImportOrRequireCalls(file) {
101139                 var r = /import|require/g;
101140                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101141                     var node = getNodeAtPosition(file, r.lastIndex);
101142                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101143                         imports = ts.append(imports, node.arguments[0]);
101144                     }
101145                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101146                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101147                         imports = ts.append(imports, node.arguments[0]);
101148                     }
101149                     else if (ts.isLiteralImportTypeNode(node)) {
101150                         imports = ts.append(imports, node.argument.literal);
101151                     }
101152                 }
101153             }
101154             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101155             function getNodeAtPosition(sourceFile, position) {
101156                 var current = sourceFile;
101157                 var getContainingChild = function (child) {
101158                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101159                         return child;
101160                     }
101161                 };
101162                 while (true) {
101163                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101164                     if (!child) {
101165                         return current;
101166                     }
101167                     current = child;
101168                 }
101169             }
101170         }
101171         function getLibFileFromReference(ref) {
101172             var libName = ts.toFileNameLowerCase(ref.fileName);
101173             var libFileName = ts.libMap.get(libName);
101174             if (libFileName) {
101175                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101176             }
101177         }
101178         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101179         function getSourceFileFromReference(referencingFile, ref) {
101180             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101181         }
101182         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101183             if (ts.hasExtension(fileName)) {
101184                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101185                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101186                     if (fail) {
101187                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101188                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101189                         }
101190                         else {
101191                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101192                         }
101193                     }
101194                     return undefined;
101195                 }
101196                 var sourceFile = getSourceFile(fileName);
101197                 if (fail) {
101198                     if (!sourceFile) {
101199                         var redirect = getProjectReferenceRedirect(fileName);
101200                         if (redirect) {
101201                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101202                         }
101203                         else {
101204                             fail(ts.Diagnostics.File_0_not_found, fileName);
101205                         }
101206                     }
101207                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101208                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101209                     }
101210                 }
101211                 return sourceFile;
101212             }
101213             else {
101214                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101215                 if (sourceFileNoExtension)
101216                     return sourceFileNoExtension;
101217                 if (fail && options.allowNonTsExtensions) {
101218                     fail(ts.Diagnostics.File_0_not_found, fileName);
101219                     return undefined;
101220                 }
101221                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101222                 if (fail && !sourceFileWithAddedExtension)
101223                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101224                 return sourceFileWithAddedExtension;
101225             }
101226         }
101227         /** This has side effects through `findSourceFile`. */
101228         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101229             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101230             function (diagnostic) {
101231                 var args = [];
101232                 for (var _i = 1; _i < arguments.length; _i++) {
101233                     args[_i - 1] = arguments[_i];
101234                 }
101235                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101236             }, refFile && refFile.file);
101237         }
101238         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101239             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101240             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101241             fileProcessingDiagnostics.add(refToReportErrorOn ?
101242                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101243                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101244         }
101245         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101246             var redirect = Object.create(redirectTarget);
101247             redirect.fileName = fileName;
101248             redirect.path = path;
101249             redirect.resolvedPath = resolvedPath;
101250             redirect.originalFileName = originalFileName;
101251             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101252             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101253             Object.defineProperties(redirect, {
101254                 id: {
101255                     get: function () { return this.redirectInfo.redirectTarget.id; },
101256                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101257                 },
101258                 symbol: {
101259                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101260                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101261                 },
101262             });
101263             return redirect;
101264         }
101265         // Get source file from normalized fileName
101266         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101267             if (useSourceOfProjectReferenceRedirect) {
101268                 var source = getSourceOfProjectReferenceRedirect(fileName);
101269                 // If preserveSymlinks is true, module resolution wont jump the symlink
101270                 // but the resolved real path may be the .d.ts from project reference
101271                 // Note:: Currently we try the real path only if the
101272                 // file is from node_modules to avoid having to run real path on all file paths
101273                 if (!source &&
101274                     host.realpath &&
101275                     options.preserveSymlinks &&
101276                     ts.isDeclarationFileName(fileName) &&
101277                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101278                     var realPath = host.realpath(fileName);
101279                     if (realPath !== fileName)
101280                         source = getSourceOfProjectReferenceRedirect(realPath);
101281                 }
101282                 if (source) {
101283                     var file_1 = ts.isString(source) ?
101284                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101285                         undefined;
101286                     if (file_1)
101287                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101288                     return file_1;
101289                 }
101290             }
101291             var originalFileName = fileName;
101292             if (filesByName.has(path)) {
101293                 var file_2 = filesByName.get(path);
101294                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101295                 // try to check if we've already seen this file but with a different casing in path
101296                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101297                 if (file_2 && options.forceConsistentCasingInFileNames) {
101298                     var checkedName = file_2.fileName;
101299                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101300                     if (isRedirect) {
101301                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101302                     }
101303                     // Check if it differs only in drive letters its ok to ignore that error:
101304                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101305                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101306                     if (checkedAbsolutePath !== inputAbsolutePath) {
101307                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101308                     }
101309                 }
101310                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101311                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101312                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101313                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101314                     if (!options.noResolve) {
101315                         processReferencedFiles(file_2, isDefaultLib);
101316                         processTypeReferenceDirectives(file_2);
101317                     }
101318                     if (!options.noLib) {
101319                         processLibReferenceDirectives(file_2);
101320                     }
101321                     modulesWithElidedImports.set(file_2.path, false);
101322                     processImportedModules(file_2);
101323                 }
101324                 // See if we need to reprocess the imports due to prior skipped imports
101325                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101326                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101327                         modulesWithElidedImports.set(file_2.path, false);
101328                         processImportedModules(file_2);
101329                     }
101330                 }
101331                 return file_2 || undefined;
101332             }
101333             var redirectedPath;
101334             if (refFile && !useSourceOfProjectReferenceRedirect) {
101335                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101336                 if (redirectProject) {
101337                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101338                         // Shouldnt create many to 1 mapping file in --out scenario
101339                         return undefined;
101340                     }
101341                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101342                     fileName = redirect;
101343                     // Once we start redirecting to a file, we can potentially come back to it
101344                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101345                     // end up trying to add it to the program *again* because we were tracking it via its
101346                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101347                     // to the source file we're about to find/create
101348                     redirectedPath = toPath(redirect);
101349                 }
101350             }
101351             // We haven't looked for this file, do so now and cache result
101352             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);
101353             if (packageId) {
101354                 var packageIdKey = ts.packageIdToString(packageId);
101355                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101356                 if (fileFromPackageId) {
101357                     // Some other SourceFile already exists with this package name and version.
101358                     // Instead of creating a duplicate, just redirect to the existing one.
101359                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101360                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101361                     addFileToFilesByName(dupFile, path, redirectedPath);
101362                     sourceFileToPackageName.set(path, packageId.name);
101363                     processingOtherFiles.push(dupFile);
101364                     return dupFile;
101365                 }
101366                 else if (file) {
101367                     // This is the first source file to have this packageId.
101368                     packageIdToSourceFile.set(packageIdKey, file);
101369                     sourceFileToPackageName.set(path, packageId.name);
101370                 }
101371             }
101372             addFileToFilesByName(file, path, redirectedPath);
101373             if (file) {
101374                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101375                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101376                 file.path = path;
101377                 file.resolvedPath = toPath(fileName);
101378                 file.originalFileName = originalFileName;
101379                 addFileToRefFileMap(fileName, file, refFile);
101380                 if (host.useCaseSensitiveFileNames()) {
101381                     var pathLowerCase = ts.toFileNameLowerCase(path);
101382                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101383                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101384                     if (existingFile) {
101385                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101386                     }
101387                     else {
101388                         filesByNameIgnoreCase.set(pathLowerCase, file);
101389                     }
101390                 }
101391                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101392                 if (!options.noResolve) {
101393                     processReferencedFiles(file, isDefaultLib);
101394                     processTypeReferenceDirectives(file);
101395                 }
101396                 if (!options.noLib) {
101397                     processLibReferenceDirectives(file);
101398                 }
101399                 // always process imported modules to record module name resolutions
101400                 processImportedModules(file);
101401                 if (isDefaultLib) {
101402                     processingDefaultLibFiles.push(file);
101403                 }
101404                 else {
101405                     processingOtherFiles.push(file);
101406                 }
101407             }
101408             return file;
101409         }
101410         function addFileToRefFileMap(referencedFileName, file, refFile) {
101411             if (refFile && file) {
101412                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101413                     referencedFileName: referencedFileName,
101414                     kind: refFile.kind,
101415                     index: refFile.index,
101416                     file: refFile.file.path
101417                 });
101418             }
101419         }
101420         function addFileToFilesByName(file, path, redirectedPath) {
101421             if (redirectedPath) {
101422                 filesByName.set(redirectedPath, file);
101423                 filesByName.set(path, file || false);
101424             }
101425             else {
101426                 filesByName.set(path, file);
101427             }
101428         }
101429         function getProjectReferenceRedirect(fileName) {
101430             var referencedProject = getProjectReferenceRedirectProject(fileName);
101431             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101432         }
101433         function getProjectReferenceRedirectProject(fileName) {
101434             // Ignore dts or any json files
101435             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101436                 return undefined;
101437             }
101438             // If this file is produced by a referenced project, we need to rewrite it to
101439             // look in the output folder of the referenced project rather than the input
101440             return getResolvedProjectReferenceToRedirect(fileName);
101441         }
101442         function getProjectReferenceOutputName(referencedProject, fileName) {
101443             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101444             return out ?
101445                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101446                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101447         }
101448         /**
101449          * Get the referenced project if the file is input file from that reference project
101450          */
101451         function getResolvedProjectReferenceToRedirect(fileName) {
101452             if (mapFromFileToProjectReferenceRedirects === undefined) {
101453                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101454                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101455                     // not input file from the referenced project, ignore
101456                     if (referencedProject &&
101457                         toPath(options.configFilePath) !== referenceProjectPath) {
101458                         referencedProject.commandLine.fileNames.forEach(function (f) {
101459                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101460                         });
101461                     }
101462                 });
101463             }
101464             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101465             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101466         }
101467         function forEachResolvedProjectReference(cb) {
101468             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101469                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101470                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101471                 return cb(resolvedRef, resolvedRefPath);
101472             });
101473         }
101474         function getSourceOfProjectReferenceRedirect(file) {
101475             if (!ts.isDeclarationFileName(file))
101476                 return undefined;
101477             if (mapFromToProjectReferenceRedirectSource === undefined) {
101478                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101479                 forEachResolvedProjectReference(function (resolvedRef) {
101480                     if (resolvedRef) {
101481                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101482                         if (out) {
101483                             // Dont know which source file it means so return true?
101484                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101485                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101486                         }
101487                         else {
101488                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101489                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101490                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101491                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101492                                 }
101493                             });
101494                         }
101495                     }
101496                 });
101497             }
101498             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101499         }
101500         function isSourceOfProjectReferenceRedirect(fileName) {
101501             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101502         }
101503         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101504             var seenResolvedRefs;
101505             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101506             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101507                 // Visit project references first
101508                 if (cbRef) {
101509                     var result = cbRef(projectReferences, parent);
101510                     if (result) {
101511                         return result;
101512                     }
101513                 }
101514                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101515                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101516                         // ignore recursives
101517                         return undefined;
101518                     }
101519                     var result = cbResolvedRef(resolvedRef, index, parent);
101520                     if (result) {
101521                         return result;
101522                     }
101523                     if (!resolvedRef)
101524                         return undefined;
101525                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101526                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101527                 });
101528             }
101529         }
101530         function getResolvedProjectReferenceByPath(projectReferencePath) {
101531             if (!projectReferenceRedirects) {
101532                 return undefined;
101533             }
101534             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101535         }
101536         function processReferencedFiles(file, isDefaultLib) {
101537             ts.forEach(file.referencedFiles, function (ref, index) {
101538                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101539                 processSourceFile(referencedFileName, isDefaultLib, 
101540                 /*ignoreNoDefaultLib*/ false, 
101541                 /*packageId*/ undefined, {
101542                     kind: ts.RefFileKind.ReferenceFile,
101543                     index: index,
101544                     file: file,
101545                     pos: ref.pos,
101546                     end: ref.end
101547                 });
101548             });
101549         }
101550         function processTypeReferenceDirectives(file) {
101551             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101552             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101553             if (!typeDirectives) {
101554                 return;
101555             }
101556             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101557             for (var i = 0; i < typeDirectives.length; i++) {
101558                 var ref = file.typeReferenceDirectives[i];
101559                 var resolvedTypeReferenceDirective = resolutions[i];
101560                 // store resolved type directive on the file
101561                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101562                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101563                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101564                     kind: ts.RefFileKind.TypeReferenceDirective,
101565                     index: i,
101566                     file: file,
101567                     pos: ref.pos,
101568                     end: ref.end
101569                 });
101570             }
101571         }
101572         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101573             // If we already found this library as a primary reference - nothing to do
101574             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101575             if (previousResolution && previousResolution.primary) {
101576                 return;
101577             }
101578             var saveResolution = true;
101579             if (resolvedTypeReferenceDirective) {
101580                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101581                     currentNodeModulesDepth++;
101582                 if (resolvedTypeReferenceDirective.primary) {
101583                     // resolved from the primary path
101584                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101585                 }
101586                 else {
101587                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101588                     // for sameness and possibly issue an error
101589                     if (previousResolution) {
101590                         // Don't bother reading the file again if it's the same file.
101591                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101592                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101593                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101594                             if (otherFileText !== existingFile_1.text) {
101595                                 // Try looking up ref for original file
101596                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101597                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101598                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101599                                     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) :
101600                                     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));
101601                             }
101602                         }
101603                         // don't overwrite previous resolution result
101604                         saveResolution = false;
101605                     }
101606                     else {
101607                         // First resolution of this library
101608                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101609                     }
101610                 }
101611                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101612                     currentNodeModulesDepth--;
101613             }
101614             else {
101615                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101616             }
101617             if (saveResolution) {
101618                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101619             }
101620         }
101621         function processLibReferenceDirectives(file) {
101622             ts.forEach(file.libReferenceDirectives, function (libReference) {
101623                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101624                 var libFileName = ts.libMap.get(libName);
101625                 if (libFileName) {
101626                     // we ignore any 'no-default-lib' reference set on this file.
101627                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101628                 }
101629                 else {
101630                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101631                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101632                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101633                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101634                 }
101635             });
101636         }
101637         function createRefFileDiagnostic(refFile, message) {
101638             var args = [];
101639             for (var _i = 2; _i < arguments.length; _i++) {
101640                 args[_i - 2] = arguments[_i];
101641             }
101642             if (!refFile) {
101643                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101644             }
101645             else {
101646                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101647             }
101648         }
101649         function getCanonicalFileName(fileName) {
101650             return host.getCanonicalFileName(fileName);
101651         }
101652         function processImportedModules(file) {
101653             collectExternalModuleReferences(file);
101654             if (file.imports.length || file.moduleAugmentations.length) {
101655                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101656                 var moduleNames = getModuleNames(file);
101657                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101658                 ts.Debug.assert(resolutions.length === moduleNames.length);
101659                 for (var i = 0; i < moduleNames.length; i++) {
101660                     var resolution = resolutions[i];
101661                     ts.setResolvedModule(file, moduleNames[i], resolution);
101662                     if (!resolution) {
101663                         continue;
101664                     }
101665                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101666                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101667                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101668                     var resolvedFileName = resolution.resolvedFileName;
101669                     if (isFromNodeModulesSearch) {
101670                         currentNodeModulesDepth++;
101671                     }
101672                     // add file to program only if:
101673                     // - resolution was successful
101674                     // - noResolve is falsy
101675                     // - module name comes from the list of imports
101676                     // - it's not a top level JavaScript module that exceeded the search max
101677                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101678                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101679                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101680                     var shouldAddFile = resolvedFileName
101681                         && !getResolutionDiagnostic(options, resolution)
101682                         && !options.noResolve
101683                         && i < file.imports.length
101684                         && !elideImport
101685                         && !(isJsFile && !options.allowJs)
101686                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101687                     if (elideImport) {
101688                         modulesWithElidedImports.set(file.path, true);
101689                     }
101690                     else if (shouldAddFile) {
101691                         var path = toPath(resolvedFileName);
101692                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101693                         findSourceFile(resolvedFileName, path, 
101694                         /*isDefaultLib*/ false, 
101695                         /*ignoreNoDefaultLib*/ false, {
101696                             kind: ts.RefFileKind.Import,
101697                             index: i,
101698                             file: file,
101699                             pos: pos,
101700                             end: file.imports[i].end
101701                         }, resolution.packageId);
101702                     }
101703                     if (isFromNodeModulesSearch) {
101704                         currentNodeModulesDepth--;
101705                     }
101706                 }
101707             }
101708             else {
101709                 // no imports - drop cached module resolutions
101710                 file.resolvedModules = undefined;
101711             }
101712         }
101713         function computeCommonSourceDirectory(sourceFiles) {
101714             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101715             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101716         }
101717         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101718             var allFilesBelongToPath = true;
101719             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101720             var rootPaths;
101721             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101722                 var sourceFile = sourceFiles_2[_i];
101723                 if (!sourceFile.isDeclarationFile) {
101724                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101725                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101726                         if (!rootPaths)
101727                             rootPaths = ts.arrayToSet(rootNames, toPath);
101728                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101729                         allFilesBelongToPath = false;
101730                     }
101731                 }
101732             }
101733             return allFilesBelongToPath;
101734         }
101735         function parseProjectReferenceConfigFile(ref) {
101736             if (!projectReferenceRedirects) {
101737                 projectReferenceRedirects = ts.createMap();
101738             }
101739             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101740             var refPath = resolveProjectReferencePath(ref);
101741             var sourceFilePath = toPath(refPath);
101742             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101743             if (fromCache !== undefined) {
101744                 return fromCache || undefined;
101745             }
101746             var commandLine;
101747             var sourceFile;
101748             if (host.getParsedCommandLine) {
101749                 commandLine = host.getParsedCommandLine(refPath);
101750                 if (!commandLine) {
101751                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101752                     projectReferenceRedirects.set(sourceFilePath, false);
101753                     return undefined;
101754                 }
101755                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101756                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101757                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101758             }
101759             else {
101760                 // An absolute path pointing to the containing directory of the config file
101761                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101762                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101763                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101764                 if (sourceFile === undefined) {
101765                     projectReferenceRedirects.set(sourceFilePath, false);
101766                     return undefined;
101767                 }
101768                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101769             }
101770             sourceFile.fileName = refPath;
101771             sourceFile.path = sourceFilePath;
101772             sourceFile.resolvedPath = sourceFilePath;
101773             sourceFile.originalFileName = refPath;
101774             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101775             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101776             if (commandLine.projectReferences) {
101777                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101778             }
101779             return resolvedRef;
101780         }
101781         function verifyCompilerOptions() {
101782             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101783                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101784             }
101785             if (options.isolatedModules) {
101786                 if (options.out) {
101787                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101788                 }
101789                 if (options.outFile) {
101790                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101791                 }
101792             }
101793             if (options.inlineSourceMap) {
101794                 if (options.sourceMap) {
101795                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101796                 }
101797                 if (options.mapRoot) {
101798                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101799                 }
101800             }
101801             if (options.paths && options.baseUrl === undefined) {
101802                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101803             }
101804             if (options.composite) {
101805                 if (options.declaration === false) {
101806                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101807                 }
101808                 if (options.incremental === false) {
101809                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101810                 }
101811             }
101812             if (options.tsBuildInfoFile) {
101813                 if (!ts.isIncrementalCompilation(options)) {
101814                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
101815                 }
101816             }
101817             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
101818                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
101819             }
101820             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
101821                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
101822             }
101823             verifyProjectReferences();
101824             // List of collected files is complete; validate exhautiveness if this is a project with a file list
101825             if (options.composite) {
101826                 var rootPaths = ts.arrayToSet(rootNames, toPath);
101827                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
101828                     var file = files_3[_i];
101829                     // Ignore file that is not emitted
101830                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
101831                         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 || "");
101832                     }
101833                 }
101834             }
101835             if (options.paths) {
101836                 for (var key in options.paths) {
101837                     if (!ts.hasProperty(options.paths, key)) {
101838                         continue;
101839                     }
101840                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
101841                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
101842                     }
101843                     if (ts.isArray(options.paths[key])) {
101844                         var len = options.paths[key].length;
101845                         if (len === 0) {
101846                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
101847                         }
101848                         for (var i = 0; i < len; i++) {
101849                             var subst = options.paths[key][i];
101850                             var typeOfSubst = typeof subst;
101851                             if (typeOfSubst === "string") {
101852                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
101853                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
101854                                 }
101855                             }
101856                             else {
101857                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
101858                             }
101859                         }
101860                     }
101861                     else {
101862                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
101863                     }
101864                 }
101865             }
101866             if (!options.sourceMap && !options.inlineSourceMap) {
101867                 if (options.inlineSources) {
101868                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
101869                 }
101870                 if (options.sourceRoot) {
101871                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
101872                 }
101873             }
101874             if (options.out && options.outFile) {
101875                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
101876             }
101877             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
101878                 // Error to specify --mapRoot without --sourcemap
101879                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
101880             }
101881             if (options.declarationDir) {
101882                 if (!ts.getEmitDeclarations(options)) {
101883                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
101884                 }
101885                 if (options.out || options.outFile) {
101886                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
101887                 }
101888             }
101889             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
101890                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
101891             }
101892             if (options.lib && options.noLib) {
101893                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
101894             }
101895             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
101896                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
101897             }
101898             var languageVersion = options.target || 0 /* ES3 */;
101899             var outFile = options.outFile || options.out;
101900             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
101901             if (options.isolatedModules) {
101902                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
101903                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
101904                 }
101905                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
101906                 if (firstNonExternalModuleSourceFile) {
101907                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
101908                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
101909                 }
101910             }
101911             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
101912                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
101913                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101914                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
101915             }
101916             // Cannot specify module gen that isn't amd or system with --out
101917             if (outFile && !options.emitDeclarationOnly) {
101918                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
101919                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
101920                 }
101921                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
101922                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101923                     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"));
101924                 }
101925             }
101926             if (options.resolveJsonModule) {
101927                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
101928                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
101929                 }
101930                 // Any emit other than common js, amd, es2015 or esnext is error
101931                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
101932                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
101933                 }
101934             }
101935             // there has to be common source directory if user specified --outdir || --sourceRoot
101936             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
101937             if (options.outDir || // there is --outDir specified
101938                 options.sourceRoot || // there is --sourceRoot specified
101939                 options.mapRoot) { // there is --mapRoot specified
101940                 // Precalculate and cache the common source directory
101941                 var dir = getCommonSourceDirectory();
101942                 // 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
101943                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
101944                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
101945                 }
101946             }
101947             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
101948                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
101949             }
101950             if (options.checkJs && !options.allowJs) {
101951                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
101952             }
101953             if (options.emitDeclarationOnly) {
101954                 if (!ts.getEmitDeclarations(options)) {
101955                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
101956                 }
101957                 if (options.noEmit) {
101958                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
101959                 }
101960             }
101961             if (options.emitDecoratorMetadata &&
101962                 !options.experimentalDecorators) {
101963                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
101964             }
101965             if (options.jsxFactory) {
101966                 if (options.reactNamespace) {
101967                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
101968                 }
101969                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
101970                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
101971                 }
101972             }
101973             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
101974                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
101975             }
101976             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
101977             if (!options.noEmit && !options.suppressOutputPathCheck) {
101978                 var emitHost = getEmitHost();
101979                 var emitFilesSeen_1 = ts.createMap();
101980                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
101981                     if (!options.emitDeclarationOnly) {
101982                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
101983                     }
101984                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
101985                 });
101986             }
101987             // Verify that all the emit files are unique and don't overwrite input files
101988             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
101989                 if (emitFileName) {
101990                     var emitFilePath = toPath(emitFileName);
101991                     // Report error if the output overwrites input file
101992                     if (filesByName.has(emitFilePath)) {
101993                         var chain = void 0;
101994                         if (!options.configFilePath) {
101995                             // The program is from either an inferred project or an external project
101996                             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);
101997                         }
101998                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
101999                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102000                     }
102001                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102002                     // Report error if multiple files write into same file
102003                     if (emitFilesSeen.has(emitFileKey)) {
102004                         // Already seen the same emit file - report error
102005                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102006                     }
102007                     else {
102008                         emitFilesSeen.set(emitFileKey, true);
102009                     }
102010                 }
102011             }
102012         }
102013         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102014             var _a, _b;
102015             var args = [];
102016             for (var _i = 2; _i < arguments.length; _i++) {
102017                 args[_i - 2] = arguments[_i];
102018             }
102019             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102020             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102021             var pos, end;
102022             switch (kind) {
102023                 case ts.RefFileKind.Import:
102024                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102025                     end = refFile.imports[index].end;
102026                     break;
102027                 case ts.RefFileKind.ReferenceFile:
102028                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102029                     break;
102030                 case ts.RefFileKind.TypeReferenceDirective:
102031                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102032                     break;
102033                 default:
102034                     return ts.Debug.assertNever(kind);
102035             }
102036             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102037         }
102038         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102039             var args = [];
102040             for (var _i = 3; _i < arguments.length; _i++) {
102041                 args[_i - 3] = arguments[_i];
102042             }
102043             var refPaths = refFileMap && refFileMap.get(file.path);
102044             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102045                 ts.elementAt(refPaths, 0);
102046             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102047         }
102048         function verifyProjectReferences() {
102049             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102050             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102051                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102052                 var parentFile = parent && parent.sourceFile;
102053                 if (!resolvedRef) {
102054                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102055                     return;
102056                 }
102057                 var options = resolvedRef.commandLine.options;
102058                 if (!options.composite) {
102059                     // ok to not have composite if the current program is container only
102060                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102061                     if (inputs.length) {
102062                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102063                     }
102064                 }
102065                 if (ref.prepend) {
102066                     var out = options.outFile || options.out;
102067                     if (out) {
102068                         if (!host.fileExists(out)) {
102069                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102070                         }
102071                     }
102072                     else {
102073                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102074                     }
102075                 }
102076                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102077                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102078                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102079                 }
102080             });
102081         }
102082         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102083             var needCompilerDiagnostic = true;
102084             var pathsSyntax = getOptionPathsSyntax();
102085             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102086                 var pathProp = pathsSyntax_1[_i];
102087                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102088                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102089                         var keyProps = _b[_a];
102090                         var initializer = keyProps.initializer;
102091                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102092                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102093                             needCompilerDiagnostic = false;
102094                         }
102095                     }
102096                 }
102097             }
102098             if (needCompilerDiagnostic) {
102099                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102100             }
102101         }
102102         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102103             var needCompilerDiagnostic = true;
102104             var pathsSyntax = getOptionPathsSyntax();
102105             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102106                 var pathProp = pathsSyntax_2[_i];
102107                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102108                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102109                     needCompilerDiagnostic = false;
102110                 }
102111             }
102112             if (needCompilerDiagnostic) {
102113                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102114             }
102115         }
102116         function getOptionsSyntaxByName(name) {
102117             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102118             if (compilerOptionsObjectLiteralSyntax) {
102119                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102120             }
102121             return undefined;
102122         }
102123         function getOptionPathsSyntax() {
102124             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102125         }
102126         function createDiagnosticForOptionName(message, option1, option2, option3) {
102127             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102128         }
102129         function createOptionValueDiagnostic(option1, message, arg0) {
102130             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102131         }
102132         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102133             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102134             if (referencesSyntax && referencesSyntax.elements.length > index) {
102135                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102136             }
102137             else {
102138                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102139             }
102140         }
102141         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102142             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102143             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102144                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102145             if (needCompilerDiagnostic) {
102146                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102147             }
102148         }
102149         function getCompilerOptionsObjectLiteralSyntax() {
102150             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102151                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102152                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102153                 if (jsonObjectLiteral) {
102154                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102155                         var prop = _a[_i];
102156                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102157                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102158                             break;
102159                         }
102160                     }
102161                 }
102162             }
102163             return _compilerOptionsObjectLiteralSyntax;
102164         }
102165         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102166             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102167             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102168                 var prop = props_3[_i];
102169                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102170             }
102171             return !!props.length;
102172         }
102173         function blockEmittingOfFile(emitFileName, diag) {
102174             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102175             programDiagnostics.add(diag);
102176         }
102177         function isEmittedFile(file) {
102178             if (options.noEmit) {
102179                 return false;
102180             }
102181             // If this is source file, its not emitted file
102182             var filePath = toPath(file);
102183             if (getSourceFileByPath(filePath)) {
102184                 return false;
102185             }
102186             // If options have --outFile or --out just check that
102187             var out = options.outFile || options.out;
102188             if (out) {
102189                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102190             }
102191             // If declarationDir is specified, return if its a file in that directory
102192             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102193                 return true;
102194             }
102195             // If --outDir, check if file is in that directory
102196             if (options.outDir) {
102197                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102198             }
102199             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102200                 // Otherwise just check if sourceFile with the name exists
102201                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102202                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102203                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102204             }
102205             return false;
102206         }
102207         function isSameFile(file1, file2) {
102208             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102209         }
102210         function getProbableSymlinks() {
102211             if (host.getSymlinks) {
102212                 return host.getSymlinks();
102213             }
102214             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102215         }
102216     }
102217     ts.createProgram = createProgram;
102218     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102219         var mapOfDeclarationDirectories;
102220         var symlinkedDirectories;
102221         var symlinkedFiles;
102222         var originalFileExists = host.compilerHost.fileExists;
102223         var originalDirectoryExists = host.compilerHost.directoryExists;
102224         var originalGetDirectories = host.compilerHost.getDirectories;
102225         var originalRealpath = host.compilerHost.realpath;
102226         if (!host.useSourceOfProjectReferenceRedirect)
102227             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102228         host.compilerHost.fileExists = fileExists;
102229         if (originalDirectoryExists) {
102230             // This implementation of directoryExists checks if the directory being requested is
102231             // directory of .d.ts file for the referenced Project.
102232             // If it is it returns true irrespective of whether that directory exists on host
102233             host.compilerHost.directoryExists = function (path) {
102234                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102235                     handleDirectoryCouldBeSymlink(path);
102236                     return true;
102237                 }
102238                 if (!host.getResolvedProjectReferences())
102239                     return false;
102240                 if (!mapOfDeclarationDirectories) {
102241                     mapOfDeclarationDirectories = ts.createMap();
102242                     host.forEachResolvedProjectReference(function (ref) {
102243                         if (!ref)
102244                             return;
102245                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102246                         if (out) {
102247                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102248                         }
102249                         else {
102250                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102251                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102252                             if (declarationDir) {
102253                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102254                             }
102255                         }
102256                     });
102257                 }
102258                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102259             };
102260         }
102261         if (originalGetDirectories) {
102262             // Call getDirectories only if directory actually present on the host
102263             // This is needed to ensure that we arent getting directories that we fake about presence for
102264             host.compilerHost.getDirectories = function (path) {
102265                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102266                     originalGetDirectories.call(host.compilerHost, path) :
102267                     [];
102268             };
102269         }
102270         // This is something we keep for life time of the host
102271         if (originalRealpath) {
102272             host.compilerHost.realpath = function (s) {
102273                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102274                     originalRealpath.call(host.compilerHost, s);
102275             };
102276         }
102277         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102278         function onProgramCreateComplete() {
102279             host.compilerHost.fileExists = originalFileExists;
102280             host.compilerHost.directoryExists = originalDirectoryExists;
102281             host.compilerHost.getDirectories = originalGetDirectories;
102282             // DO not revert realpath as it could be used later
102283         }
102284         // This implementation of fileExists checks if the file being requested is
102285         // .d.ts file for the referenced Project.
102286         // If it is it returns true irrespective of whether that file exists on host
102287         function fileExists(file) {
102288             if (originalFileExists.call(host.compilerHost, file))
102289                 return true;
102290             if (!host.getResolvedProjectReferences())
102291                 return false;
102292             if (!ts.isDeclarationFileName(file))
102293                 return false;
102294             // Project references go to source file instead of .d.ts file
102295             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102296         }
102297         function fileExistsIfProjectReferenceDts(file) {
102298             var source = host.getSourceOfProjectReferenceRedirect(file);
102299             return source !== undefined ?
102300                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102301                 undefined;
102302         }
102303         function directoryExistsIfProjectReferenceDeclDir(dir) {
102304             var dirPath = host.toPath(dir);
102305             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102306             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102307                 // Any parent directory of declaration dir
102308                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102309                 // Any directory inside declaration dir
102310                 ts.startsWith(dirPath, declDirPath + "/"); });
102311         }
102312         function handleDirectoryCouldBeSymlink(directory) {
102313             if (!host.getResolvedProjectReferences())
102314                 return;
102315             // Because we already watch node_modules, handle symlinks in there
102316             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102317                 return;
102318             if (!symlinkedDirectories)
102319                 symlinkedDirectories = ts.createMap();
102320             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102321             if (symlinkedDirectories.has(directoryPath))
102322                 return;
102323             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102324             var realPath;
102325             if (real === directory ||
102326                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102327                 // not symlinked
102328                 symlinkedDirectories.set(directoryPath, false);
102329                 return;
102330             }
102331             symlinkedDirectories.set(directoryPath, {
102332                 real: ts.ensureTrailingDirectorySeparator(real),
102333                 realPath: realPath
102334             });
102335         }
102336         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102337             var fileOrDirectoryExistsUsingSource = isFile ?
102338                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102339                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102340             // Check current directory or file
102341             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102342             if (result !== undefined)
102343                 return result;
102344             if (!symlinkedDirectories)
102345                 return false;
102346             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102347             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102348                 return false;
102349             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102350                 return true;
102351             // If it contains node_modules check if its one of the symlinked path we know of
102352             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102353                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102354                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102355                     return undefined;
102356                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102357                 if (isFile && result) {
102358                     if (!symlinkedFiles)
102359                         symlinkedFiles = ts.createMap();
102360                     // Store the real path for the file'
102361                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102362                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102363                 }
102364                 return result;
102365             }) || false;
102366         }
102367     }
102368     /*@internal*/
102369     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102370         var options = program.getCompilerOptions();
102371         if (options.noEmit) {
102372             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102373         }
102374         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102375         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102376         // get any preEmit diagnostics, not just the ones
102377         if (!options.noEmitOnError)
102378             return undefined;
102379         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102380         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102381             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102382         }
102383         return diagnostics.length > 0 ?
102384             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102385             undefined;
102386     }
102387     ts.handleNoEmitOptions = handleNoEmitOptions;
102388     /* @internal */
102389     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102390         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102391         return {
102392             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102393             readDirectory: function (root, extensions, excludes, includes, depth) {
102394                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102395                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102396             },
102397             readFile: function (f) { return directoryStructureHost.readFile(f); },
102398             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102399             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102400             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102401             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102402         };
102403     }
102404     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102405     /* @internal */
102406     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102407         if (!projectReferences)
102408             return ts.emptyArray;
102409         var nodes;
102410         for (var i = 0; i < projectReferences.length; i++) {
102411             var ref = projectReferences[i];
102412             var resolvedRefOpts = getCommandLine(ref, i);
102413             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102414                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102415                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102416                 if (!out)
102417                     continue;
102418                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102419                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102420                 (nodes || (nodes = [])).push(node);
102421             }
102422         }
102423         return nodes || ts.emptyArray;
102424     }
102425     ts.createPrependNodes = createPrependNodes;
102426     function resolveProjectReferencePath(hostOrRef, ref) {
102427         var passedInRef = ref ? ref : hostOrRef;
102428         return ts.resolveConfigFileProjectName(passedInRef.path);
102429     }
102430     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102431     /* @internal */
102432     /**
102433      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102434      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102435      * This returns a diagnostic even if the module will be an untyped module.
102436      */
102437     function getResolutionDiagnostic(options, _a) {
102438         var extension = _a.extension;
102439         switch (extension) {
102440             case ".ts" /* Ts */:
102441             case ".d.ts" /* Dts */:
102442                 // These are always allowed.
102443                 return undefined;
102444             case ".tsx" /* Tsx */:
102445                 return needJsx();
102446             case ".jsx" /* Jsx */:
102447                 return needJsx() || needAllowJs();
102448             case ".js" /* Js */:
102449                 return needAllowJs();
102450             case ".json" /* Json */:
102451                 return needResolveJsonModule();
102452         }
102453         function needJsx() {
102454             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102455         }
102456         function needAllowJs() {
102457             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;
102458         }
102459         function needResolveJsonModule() {
102460             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102461         }
102462     }
102463     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102464     function getModuleNames(_a) {
102465         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102466         var res = imports.map(function (i) { return i.text; });
102467         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102468             var aug = moduleAugmentations_1[_i];
102469             if (aug.kind === 10 /* StringLiteral */) {
102470                 res.push(aug.text);
102471             }
102472             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102473         }
102474         return res;
102475     }
102476 })(ts || (ts = {}));
102477 /*@internal*/
102478 var ts;
102479 (function (ts) {
102480     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102481         var outputFiles = [];
102482         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102483         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102484         function writeFile(fileName, text, writeByteOrderMark) {
102485             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102486         }
102487     }
102488     ts.getFileEmitOutput = getFileEmitOutput;
102489     var BuilderState;
102490     (function (BuilderState) {
102491         /**
102492          * Get the referencedFile from the imported module symbol
102493          */
102494         function getReferencedFileFromImportedModuleSymbol(symbol) {
102495             if (symbol.declarations && symbol.declarations[0]) {
102496                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102497                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102498             }
102499         }
102500         /**
102501          * Get the referencedFile from the import name node from file
102502          */
102503         function getReferencedFileFromImportLiteral(checker, importName) {
102504             var symbol = checker.getSymbolAtLocation(importName);
102505             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102506         }
102507         /**
102508          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102509          */
102510         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102511             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102512         }
102513         /**
102514          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102515          */
102516         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102517             var referencedFiles;
102518             // We need to use a set here since the code can contain the same import twice,
102519             // but that will only be one dependency.
102520             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102521             if (sourceFile.imports && sourceFile.imports.length > 0) {
102522                 var checker = program.getTypeChecker();
102523                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102524                     var importName = _a[_i];
102525                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102526                     if (declarationSourceFilePath) {
102527                         addReferencedFile(declarationSourceFilePath);
102528                     }
102529                 }
102530             }
102531             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102532             // Handle triple slash references
102533             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102534                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102535                     var referencedFile = _c[_b];
102536                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102537                     addReferencedFile(referencedPath);
102538                 }
102539             }
102540             // Handle type reference directives
102541             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102542                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102543                     if (!resolvedTypeReferenceDirective) {
102544                         return;
102545                     }
102546                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102547                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102548                     addReferencedFile(typeFilePath);
102549                 });
102550             }
102551             // Add module augmentation as references
102552             if (sourceFile.moduleAugmentations.length) {
102553                 var checker = program.getTypeChecker();
102554                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102555                     var moduleName = _e[_d];
102556                     if (!ts.isStringLiteral(moduleName)) {
102557                         continue;
102558                     }
102559                     var symbol = checker.getSymbolAtLocation(moduleName);
102560                     if (!symbol) {
102561                         continue;
102562                     }
102563                     // Add any file other than our own as reference
102564                     addReferenceFromAmbientModule(symbol);
102565                 }
102566             }
102567             // From ambient modules
102568             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102569                 var ambientModule = _g[_f];
102570                 if (ambientModule.declarations.length > 1) {
102571                     addReferenceFromAmbientModule(ambientModule);
102572                 }
102573             }
102574             return referencedFiles;
102575             function addReferenceFromAmbientModule(symbol) {
102576                 // Add any file other than our own as reference
102577                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102578                     var declaration = _a[_i];
102579                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102580                     if (declarationSourceFile &&
102581                         declarationSourceFile !== sourceFile) {
102582                         addReferencedFile(declarationSourceFile.resolvedPath);
102583                     }
102584                 }
102585             }
102586             function addReferencedFile(referencedPath) {
102587                 if (!referencedFiles) {
102588                     referencedFiles = ts.createMap();
102589                 }
102590                 referencedFiles.set(referencedPath, true);
102591             }
102592         }
102593         /**
102594          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102595          */
102596         function canReuseOldState(newReferencedMap, oldState) {
102597             return oldState && !oldState.referencedMap === !newReferencedMap;
102598         }
102599         BuilderState.canReuseOldState = canReuseOldState;
102600         /**
102601          * Creates the state of file references and signature for the new program from oldState if it is safe
102602          */
102603         function create(newProgram, getCanonicalFileName, oldState) {
102604             var fileInfos = ts.createMap();
102605             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102606             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102607             var hasCalledUpdateShapeSignature = ts.createMap();
102608             var useOldState = canReuseOldState(referencedMap, oldState);
102609             // Create the reference map, and set the file infos
102610             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102611                 var sourceFile = _a[_i];
102612                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102613                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102614                 if (referencedMap) {
102615                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102616                     if (newReferences) {
102617                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102618                     }
102619                     // Copy old visible to outside files map
102620                     if (useOldState) {
102621                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102622                         if (exportedModules) {
102623                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102624                         }
102625                     }
102626                 }
102627                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102628             }
102629             return {
102630                 fileInfos: fileInfos,
102631                 referencedMap: referencedMap,
102632                 exportedModulesMap: exportedModulesMap,
102633                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102634             };
102635         }
102636         BuilderState.create = create;
102637         /**
102638          * Releases needed properties
102639          */
102640         function releaseCache(state) {
102641             state.allFilesExcludingDefaultLibraryFile = undefined;
102642             state.allFileNames = undefined;
102643         }
102644         BuilderState.releaseCache = releaseCache;
102645         /**
102646          * Creates a clone of the state
102647          */
102648         function clone(state) {
102649             var fileInfos = ts.createMap();
102650             state.fileInfos.forEach(function (value, key) {
102651                 fileInfos.set(key, __assign({}, value));
102652             });
102653             // Dont need to backup allFiles info since its cache anyway
102654             return {
102655                 fileInfos: fileInfos,
102656                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102657                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102658                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102659             };
102660         }
102661         BuilderState.clone = clone;
102662         /**
102663          * Gets the files affected by the path from the program
102664          */
102665         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102666             // Since the operation could be cancelled, the signatures are always stored in the cache
102667             // They will be committed once it is safe to use them
102668             // eg when calling this api from tsserver, if there is no cancellation of the operation
102669             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102670             var signatureCache = cacheToUpdateSignature || ts.createMap();
102671             var sourceFile = programOfThisState.getSourceFileByPath(path);
102672             if (!sourceFile) {
102673                 return ts.emptyArray;
102674             }
102675             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102676                 return [sourceFile];
102677             }
102678             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102679             if (!cacheToUpdateSignature) {
102680                 // Commit all the signatures in the signature cache
102681                 updateSignaturesFromCache(state, signatureCache);
102682             }
102683             return result;
102684         }
102685         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102686         /**
102687          * Updates the signatures from the cache into state's fileinfo signatures
102688          * This should be called whenever it is safe to commit the state of the builder
102689          */
102690         function updateSignaturesFromCache(state, signatureCache) {
102691             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102692         }
102693         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102694         function updateSignatureOfFile(state, signature, path) {
102695             state.fileInfos.get(path).signature = signature;
102696             state.hasCalledUpdateShapeSignature.set(path, true);
102697         }
102698         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102699         /**
102700          * Returns if the shape of the signature has changed since last emit
102701          */
102702         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102703             ts.Debug.assert(!!sourceFile);
102704             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102705             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102706             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102707                 return false;
102708             }
102709             var info = state.fileInfos.get(sourceFile.resolvedPath);
102710             if (!info)
102711                 return ts.Debug.fail();
102712             var prevSignature = info.signature;
102713             var latestSignature;
102714             if (sourceFile.isDeclarationFile) {
102715                 latestSignature = sourceFile.version;
102716                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102717                     // All the references in this file are exported
102718                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102719                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102720                 }
102721             }
102722             else {
102723                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102724                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102725                 /*customTransformers*/ undefined, 
102726                 /*forceDtsEmit*/ true);
102727                 var firstDts_1 = emitOutput_1.outputFiles &&
102728                     programOfThisState.getCompilerOptions().declarationMap ?
102729                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102730                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102731                 if (firstDts_1) {
102732                     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; })); });
102733                     latestSignature = computeHash(firstDts_1.text);
102734                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102735                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102736                     }
102737                 }
102738                 else {
102739                     latestSignature = prevSignature; // TODO: GH#18217
102740                 }
102741             }
102742             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102743             return !prevSignature || latestSignature !== prevSignature;
102744         }
102745         BuilderState.updateShapeSignature = updateShapeSignature;
102746         /**
102747          * Coverts the declaration emit result into exported modules map
102748          */
102749         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102750             if (!exportedModulesFromDeclarationEmit) {
102751                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102752                 return;
102753             }
102754             var exportedModules;
102755             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102756             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102757             function addExportedModule(exportedModulePath) {
102758                 if (exportedModulePath) {
102759                     if (!exportedModules) {
102760                         exportedModules = ts.createMap();
102761                     }
102762                     exportedModules.set(exportedModulePath, true);
102763                 }
102764             }
102765         }
102766         /**
102767          * Updates the exported modules from cache into state's exported modules map
102768          * This should be called whenever it is safe to commit the state of the builder
102769          */
102770         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102771             if (exportedModulesMapCache) {
102772                 ts.Debug.assert(!!state.exportedModulesMap);
102773                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102774                     if (exportedModules) {
102775                         state.exportedModulesMap.set(path, exportedModules);
102776                     }
102777                     else {
102778                         state.exportedModulesMap.delete(path);
102779                     }
102780                 });
102781             }
102782         }
102783         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102784         /**
102785          * Get all the dependencies of the sourceFile
102786          */
102787         function getAllDependencies(state, programOfThisState, sourceFile) {
102788             var compilerOptions = programOfThisState.getCompilerOptions();
102789             // With --out or --outFile all outputs go into single file, all files depend on each other
102790             if (compilerOptions.outFile || compilerOptions.out) {
102791                 return getAllFileNames(state, programOfThisState);
102792             }
102793             // If this is non module emit, or its a global file, it depends on all the source files
102794             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102795                 return getAllFileNames(state, programOfThisState);
102796             }
102797             // Get the references, traversing deep from the referenceMap
102798             var seenMap = ts.createMap();
102799             var queue = [sourceFile.resolvedPath];
102800             while (queue.length) {
102801                 var path = queue.pop();
102802                 if (!seenMap.has(path)) {
102803                     seenMap.set(path, true);
102804                     var references = state.referencedMap.get(path);
102805                     if (references) {
102806                         var iterator = references.keys();
102807                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102808                             queue.push(iterResult.value);
102809                         }
102810                     }
102811                 }
102812             }
102813             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
102814                 var file = programOfThisState.getSourceFileByPath(path);
102815                 return file ? file.fileName : path;
102816             }));
102817         }
102818         BuilderState.getAllDependencies = getAllDependencies;
102819         /**
102820          * Gets the names of all files from the program
102821          */
102822         function getAllFileNames(state, programOfThisState) {
102823             if (!state.allFileNames) {
102824                 var sourceFiles = programOfThisState.getSourceFiles();
102825                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
102826             }
102827             return state.allFileNames;
102828         }
102829         /**
102830          * Gets the files referenced by the the file path
102831          */
102832         function getReferencedByPaths(state, referencedFilePath) {
102833             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
102834                 var filePath = _a[0], referencesInFile = _a[1];
102835                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
102836             }));
102837         }
102838         BuilderState.getReferencedByPaths = getReferencedByPaths;
102839         /**
102840          * For script files that contains only ambient external modules, although they are not actually external module files,
102841          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
102842          * there are no point to rebuild all script files if these special files have changed. However, if any statement
102843          * in the file is not ambient external module, we treat it as a regular script file.
102844          */
102845         function containsOnlyAmbientModules(sourceFile) {
102846             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
102847                 var statement = _a[_i];
102848                 if (!ts.isModuleWithStringLiteralName(statement)) {
102849                     return false;
102850                 }
102851             }
102852             return true;
102853         }
102854         /**
102855          * Return true if file contains anything that augments to global scope we need to build them as if
102856          * they are global files as well as module
102857          */
102858         function containsGlobalScopeAugmentation(sourceFile) {
102859             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
102860         }
102861         /**
102862          * Return true if the file will invalidate all files because it affectes global scope
102863          */
102864         function isFileAffectingGlobalScope(sourceFile) {
102865             return containsGlobalScopeAugmentation(sourceFile) ||
102866                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
102867         }
102868         /**
102869          * Gets all files of the program excluding the default library file
102870          */
102871         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
102872             // Use cached result
102873             if (state.allFilesExcludingDefaultLibraryFile) {
102874                 return state.allFilesExcludingDefaultLibraryFile;
102875             }
102876             var result;
102877             if (firstSourceFile)
102878                 addSourceFile(firstSourceFile);
102879             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
102880                 var sourceFile = _a[_i];
102881                 if (sourceFile !== firstSourceFile) {
102882                     addSourceFile(sourceFile);
102883                 }
102884             }
102885             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
102886             return state.allFilesExcludingDefaultLibraryFile;
102887             function addSourceFile(sourceFile) {
102888                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
102889                     (result || (result = [])).push(sourceFile);
102890                 }
102891             }
102892         }
102893         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
102894         /**
102895          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
102896          */
102897         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
102898             var compilerOptions = programOfThisState.getCompilerOptions();
102899             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
102900             // so returning the file itself is good enough.
102901             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
102902                 return [sourceFileWithUpdatedShape];
102903             }
102904             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102905         }
102906         /**
102907          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
102908          */
102909         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102910             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
102911                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102912             }
102913             var compilerOptions = programOfThisState.getCompilerOptions();
102914             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
102915                 return [sourceFileWithUpdatedShape];
102916             }
102917             // Now we need to if each file in the referencedBy list has a shape change as well.
102918             // Because if so, its own referencedBy files need to be saved as well to make the
102919             // emitting result consistent with files on disk.
102920             var seenFileNamesMap = ts.createMap();
102921             // Start with the paths this file was referenced by
102922             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
102923             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
102924             while (queue.length > 0) {
102925                 var currentPath = queue.pop();
102926                 if (!seenFileNamesMap.has(currentPath)) {
102927                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
102928                     seenFileNamesMap.set(currentPath, currentSourceFile);
102929                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
102930                         queue.push.apply(// TODO: GH#18217
102931                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
102932                     }
102933                 }
102934             }
102935             // Return array of values that needs emit
102936             // Return array of values that needs emit
102937             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
102938         }
102939     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
102940     function cloneMapOrUndefined(map) {
102941         return map ? ts.cloneMap(map) : undefined;
102942     }
102943     ts.cloneMapOrUndefined = cloneMapOrUndefined;
102944 })(ts || (ts = {}));
102945 /*@internal*/
102946 var ts;
102947 (function (ts) {
102948     var BuilderFileEmit;
102949     (function (BuilderFileEmit) {
102950         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
102951         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
102952     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
102953     function hasSameKeys(map1, map2) {
102954         // Has same size and every key is present in both maps
102955         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
102956     }
102957     /**
102958      * Create the state so that we can iterate on changedFiles/affected files
102959      */
102960     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
102961         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
102962         state.program = newProgram;
102963         var compilerOptions = newProgram.getCompilerOptions();
102964         state.compilerOptions = compilerOptions;
102965         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
102966         if (!compilerOptions.outFile && !compilerOptions.out) {
102967             state.semanticDiagnosticsPerFile = ts.createMap();
102968         }
102969         state.changedFilesSet = ts.createMap();
102970         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
102971         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
102972         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
102973             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
102974         if (useOldState) {
102975             // Verify the sanity of old state
102976             if (!oldState.currentChangedFilePath) {
102977                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
102978                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
102979             }
102980             var changedFilesSet = oldState.changedFilesSet;
102981             if (canCopySemanticDiagnostics) {
102982                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
102983             }
102984             // Copy old state's changed files set
102985             if (changedFilesSet) {
102986                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
102987             }
102988             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
102989                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
102990                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
102991                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
102992                 state.seenAffectedFiles = ts.createMap();
102993             }
102994         }
102995         // Update changed files and copy semantic diagnostics if we can
102996         var referencedMap = state.referencedMap;
102997         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
102998         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
102999         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103000         state.fileInfos.forEach(function (info, sourceFilePath) {
103001             var oldInfo;
103002             var newReferences;
103003             // if not using old state, every file is changed
103004             if (!useOldState ||
103005                 // File wasnt present in old state
103006                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103007                 // versions dont match
103008                 oldInfo.version !== info.version ||
103009                 // Referenced files changed
103010                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103011                 // Referenced file was deleted in the new program
103012                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103013                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103014                 state.changedFilesSet.set(sourceFilePath, true);
103015             }
103016             else if (canCopySemanticDiagnostics) {
103017                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103018                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103019                     return;
103020                 }
103021                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103022                     return;
103023                 }
103024                 // Unchanged file copy diagnostics
103025                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103026                 if (diagnostics) {
103027                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103028                     if (!state.semanticDiagnosticsFromOldState) {
103029                         state.semanticDiagnosticsFromOldState = ts.createMap();
103030                     }
103031                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103032                 }
103033             }
103034         });
103035         // If the global file is removed, add all files as changed
103036         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103037             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103038                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103039         }
103040         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103041             // Add all files to affectedFilesPendingEmit since emit changed
103042             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103043             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103044             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103045         }
103046         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103047         return state;
103048     }
103049     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103050         if (!diagnostics.length)
103051             return ts.emptyArray;
103052         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103053         return diagnostics.map(function (diagnostic) {
103054             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103055             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103056             result.source = diagnostic.source;
103057             var relatedInformation = diagnostic.relatedInformation;
103058             result.relatedInformation = relatedInformation ?
103059                 relatedInformation.length ?
103060                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103061                     ts.emptyArray :
103062                 undefined;
103063             return result;
103064         });
103065         function toPath(path) {
103066             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103067         }
103068     }
103069     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103070         var file = diagnostic.file;
103071         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103072     }
103073     /**
103074      * Releases program and other related not needed properties
103075      */
103076     function releaseCache(state) {
103077         ts.BuilderState.releaseCache(state);
103078         state.program = undefined;
103079     }
103080     /**
103081      * Creates a clone of the state
103082      */
103083     function cloneBuilderProgramState(state) {
103084         var newState = ts.BuilderState.clone(state);
103085         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103086         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103087         newState.affectedFiles = state.affectedFiles;
103088         newState.affectedFilesIndex = state.affectedFilesIndex;
103089         newState.currentChangedFilePath = state.currentChangedFilePath;
103090         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103091         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103092         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103093         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103094         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103095         newState.program = state.program;
103096         newState.compilerOptions = state.compilerOptions;
103097         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103098         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103099         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103100         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103101         newState.programEmitComplete = state.programEmitComplete;
103102         return newState;
103103     }
103104     /**
103105      * Verifies that source file is ok to be used in calls that arent handled by next
103106      */
103107     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103108         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103109     }
103110     /**
103111      * This function returns the next affected file to be processed.
103112      * Note that until doneAffected is called it would keep reporting same result
103113      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103114      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103115      */
103116     function getNextAffectedFile(state, cancellationToken, computeHash) {
103117         while (true) {
103118             var affectedFiles = state.affectedFiles;
103119             if (affectedFiles) {
103120                 var seenAffectedFiles = state.seenAffectedFiles;
103121                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103122                 while (affectedFilesIndex < affectedFiles.length) {
103123                     var affectedFile = affectedFiles[affectedFilesIndex];
103124                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103125                         // Set the next affected file as seen and remove the cached semantic diagnostics
103126                         state.affectedFilesIndex = affectedFilesIndex;
103127                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103128                         return affectedFile;
103129                     }
103130                     affectedFilesIndex++;
103131                 }
103132                 // Remove the changed file from the change set
103133                 state.changedFilesSet.delete(state.currentChangedFilePath);
103134                 state.currentChangedFilePath = undefined;
103135                 // Commit the changes in file signature
103136                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103137                 state.currentAffectedFilesSignatures.clear();
103138                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103139                 state.affectedFiles = undefined;
103140             }
103141             // Get next changed file
103142             var nextKey = state.changedFilesSet.keys().next();
103143             if (nextKey.done) {
103144                 // Done
103145                 return undefined;
103146             }
103147             // With --out or --outFile all outputs go into single file
103148             // so operations are performed directly on program, return program
103149             var program = ts.Debug.checkDefined(state.program);
103150             var compilerOptions = program.getCompilerOptions();
103151             if (compilerOptions.outFile || compilerOptions.out) {
103152                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103153                 return program;
103154             }
103155             // Get next batch of affected files
103156             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103157             if (state.exportedModulesMap) {
103158                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103159             }
103160             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103161             state.currentChangedFilePath = nextKey.value;
103162             state.affectedFilesIndex = 0;
103163             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103164         }
103165     }
103166     /**
103167      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103168      */
103169     function getNextAffectedFilePendingEmit(state) {
103170         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103171         if (affectedFilesPendingEmit) {
103172             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103173             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103174                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103175                 if (affectedFile) {
103176                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103177                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103178                     if (seenKind === undefined || seenKind < emitKind) {
103179                         // emit this file
103180                         state.affectedFilesPendingEmitIndex = i;
103181                         return { affectedFile: affectedFile, emitKind: emitKind };
103182                     }
103183                 }
103184             }
103185             state.affectedFilesPendingEmit = undefined;
103186             state.affectedFilesPendingEmitKind = undefined;
103187             state.affectedFilesPendingEmitIndex = undefined;
103188         }
103189         return undefined;
103190     }
103191     /**
103192      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103193      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103194      */
103195     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103196         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103197         // If affected files is everything except default library, then nothing more to do
103198         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103199             if (!state.cleanedDiagnosticsOfLibFiles) {
103200                 state.cleanedDiagnosticsOfLibFiles = true;
103201                 var program_1 = ts.Debug.checkDefined(state.program);
103202                 var options_2 = program_1.getCompilerOptions();
103203                 ts.forEach(program_1.getSourceFiles(), function (f) {
103204                     return program_1.isSourceFileDefaultLibrary(f) &&
103205                         !ts.skipTypeChecking(f, options_2, program_1) &&
103206                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103207                 });
103208             }
103209             return;
103210         }
103211         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103212             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103213         }
103214     }
103215     /**
103216      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103217      * Also we need to make sure signature is updated for these files
103218      */
103219     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103220         removeSemanticDiagnosticsOf(state, path);
103221         if (!state.changedFilesSet.has(path)) {
103222             var program = ts.Debug.checkDefined(state.program);
103223             var sourceFile = program.getSourceFileByPath(path);
103224             if (sourceFile) {
103225                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103226                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103227                 // This ensures that we dont later during incremental builds considering wrong signature.
103228                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103229                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103230                 // If not dts emit, nothing more to do
103231                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103232                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103233                 }
103234             }
103235         }
103236         return false;
103237     }
103238     /**
103239      * Removes semantic diagnostics for path and
103240      * returns true if there are no more semantic diagnostics from the old state
103241      */
103242     function removeSemanticDiagnosticsOf(state, path) {
103243         if (!state.semanticDiagnosticsFromOldState) {
103244             return true;
103245         }
103246         state.semanticDiagnosticsFromOldState.delete(path);
103247         state.semanticDiagnosticsPerFile.delete(path);
103248         return !state.semanticDiagnosticsFromOldState.size;
103249     }
103250     function isChangedSignagure(state, path) {
103251         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103252         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103253         return newSignature !== oldSignagure;
103254     }
103255     /**
103256      * Iterate on referencing modules that export entities from affected file
103257      */
103258     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103259         // If there was change in signature (dts output) for the changed file,
103260         // then only we need to handle pending file emit
103261         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103262             return;
103263         }
103264         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103265             return;
103266         // Since isolated modules dont change js files, files affected by change in signature is itself
103267         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103268         if (state.compilerOptions.isolatedModules) {
103269             var seenFileNamesMap = ts.createMap();
103270             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103271             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103272             while (queue.length > 0) {
103273                 var currentPath = queue.pop();
103274                 if (!seenFileNamesMap.has(currentPath)) {
103275                     seenFileNamesMap.set(currentPath, true);
103276                     var result = fn(state, currentPath);
103277                     if (result && isChangedSignagure(state, currentPath)) {
103278                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103279                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103280                     }
103281                 }
103282             }
103283         }
103284         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103285         var seenFileAndExportsOfFile = ts.createMap();
103286         // Go through exported modules from cache first
103287         // If exported modules has path, all files referencing file exported from are affected
103288         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103289             return exportedModules &&
103290                 exportedModules.has(affectedFile.resolvedPath) &&
103291                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103292         })) {
103293             return;
103294         }
103295         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103296         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103297             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103298                 exportedModules.has(affectedFile.resolvedPath) &&
103299                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103300         });
103301     }
103302     /**
103303      * Iterate on files referencing referencedPath
103304      */
103305     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103306         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103307             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103308         });
103309     }
103310     /**
103311      * fn on file and iterate on anything that exports this file
103312      */
103313     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103314         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103315             return false;
103316         }
103317         if (fn(state, filePath)) {
103318             // If there are no more diagnostics from old cache, done
103319             return true;
103320         }
103321         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103322         // Go through exported modules from cache first
103323         // If exported modules has path, all files referencing file exported from are affected
103324         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103325             return exportedModules &&
103326                 exportedModules.has(filePath) &&
103327                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103328         })) {
103329             return true;
103330         }
103331         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103332         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103333             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103334                 exportedModules.has(filePath) &&
103335                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103336         })) {
103337             return true;
103338         }
103339         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103340         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103341             return referencesInFile.has(filePath) &&
103342                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103343                 fn(state, referencingFilePath);
103344         } // Dont add to seen since this is not yet done with the export removal
103345         );
103346     }
103347     /**
103348      * This is called after completing operation on the next affected file.
103349      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103350      */
103351     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103352         if (isBuildInfoEmit) {
103353             state.emittedBuildInfo = true;
103354         }
103355         else if (affected === state.program) {
103356             state.changedFilesSet.clear();
103357             state.programEmitComplete = true;
103358         }
103359         else {
103360             state.seenAffectedFiles.set(affected.resolvedPath, true);
103361             if (emitKind !== undefined) {
103362                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103363             }
103364             if (isPendingEmit) {
103365                 state.affectedFilesPendingEmitIndex++;
103366             }
103367             else {
103368                 state.affectedFilesIndex++;
103369             }
103370         }
103371     }
103372     /**
103373      * Returns the result with affected file
103374      */
103375     function toAffectedFileResult(state, result, affected) {
103376         doneWithAffectedFile(state, affected);
103377         return { result: result, affected: affected };
103378     }
103379     /**
103380      * Returns the result with affected file
103381      */
103382     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103383         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103384         return { result: result, affected: affected };
103385     }
103386     /**
103387      * Gets semantic diagnostics for the file which are
103388      * bindAndCheckDiagnostics (from cache) and program diagnostics
103389      */
103390     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103391         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103392     }
103393     /**
103394      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103395      * 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
103396      */
103397     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103398         var path = sourceFile.resolvedPath;
103399         if (state.semanticDiagnosticsPerFile) {
103400             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103401             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103402             if (cachedDiagnostics) {
103403                 return cachedDiagnostics;
103404             }
103405         }
103406         // Diagnostics werent cached, get them from program, and cache the result
103407         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103408         if (state.semanticDiagnosticsPerFile) {
103409             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103410         }
103411         return diagnostics;
103412     }
103413     /**
103414      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103415      */
103416     function getProgramBuildInfo(state, getCanonicalFileName) {
103417         if (state.compilerOptions.outFile || state.compilerOptions.out)
103418             return undefined;
103419         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103420         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103421         var fileInfos = {};
103422         state.fileInfos.forEach(function (value, key) {
103423             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103424             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103425         });
103426         var result = {
103427             fileInfos: fileInfos,
103428             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103429         };
103430         if (state.referencedMap) {
103431             var referencedMap = {};
103432             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103433                 var key = _a[_i];
103434                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103435             }
103436             result.referencedMap = referencedMap;
103437         }
103438         if (state.exportedModulesMap) {
103439             var exportedModulesMap = {};
103440             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103441                 var key = _c[_b];
103442                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103443                 // Not in temporary cache, use existing value
103444                 if (newValue === undefined)
103445                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103446                 // Value in cache and has updated value map, use that
103447                 else if (newValue)
103448                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103449             }
103450             result.exportedModulesMap = exportedModulesMap;
103451         }
103452         if (state.semanticDiagnosticsPerFile) {
103453             var semanticDiagnosticsPerFile = [];
103454             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103455                 var key = _e[_d];
103456                 var value = state.semanticDiagnosticsPerFile.get(key);
103457                 semanticDiagnosticsPerFile.push(value.length ?
103458                     [
103459                         relativeToBuildInfo(key),
103460                         state.hasReusableDiagnostic ?
103461                             value :
103462                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103463                     ] :
103464                     relativeToBuildInfo(key));
103465             }
103466             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103467         }
103468         return result;
103469         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103470             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103471         }
103472         function relativeToBuildInfo(path) {
103473             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103474         }
103475     }
103476     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103477         var result = {};
103478         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103479         for (var name in options) {
103480             if (ts.hasProperty(options, name)) {
103481                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103482             }
103483         }
103484         if (result.configFilePath) {
103485             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103486         }
103487         return result;
103488     }
103489     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103490         if (option) {
103491             if (option.type === "list") {
103492                 var values = value;
103493                 if (option.element.isFilePath && values.length) {
103494                     return values.map(relativeToBuildInfo);
103495                 }
103496             }
103497             else if (option.isFilePath) {
103498                 return relativeToBuildInfo(value);
103499             }
103500         }
103501         return value;
103502     }
103503     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103504         ts.Debug.assert(!!diagnostics.length);
103505         return diagnostics.map(function (diagnostic) {
103506             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103507             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103508             result.source = diagnostic.source;
103509             var relatedInformation = diagnostic.relatedInformation;
103510             result.relatedInformation = relatedInformation ?
103511                 relatedInformation.length ?
103512                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103513                     ts.emptyArray :
103514                 undefined;
103515             return result;
103516         });
103517     }
103518     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103519         var file = diagnostic.file;
103520         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103521     }
103522     var BuilderProgramKind;
103523     (function (BuilderProgramKind) {
103524         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103525         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103526     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103527     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103528         var host;
103529         var newProgram;
103530         var oldProgram;
103531         if (newProgramOrRootNames === undefined) {
103532             ts.Debug.assert(hostOrOptions === undefined);
103533             host = oldProgramOrHost;
103534             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103535             ts.Debug.assert(!!oldProgram);
103536             newProgram = oldProgram.getProgram();
103537         }
103538         else if (ts.isArray(newProgramOrRootNames)) {
103539             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103540             newProgram = ts.createProgram({
103541                 rootNames: newProgramOrRootNames,
103542                 options: hostOrOptions,
103543                 host: oldProgramOrHost,
103544                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103545                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103546                 projectReferences: projectReferences
103547             });
103548             host = oldProgramOrHost;
103549         }
103550         else {
103551             newProgram = newProgramOrRootNames;
103552             host = hostOrOptions;
103553             oldProgram = oldProgramOrHost;
103554             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103555         }
103556         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103557     }
103558     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103559     function createBuilderProgram(kind, _a) {
103560         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103561         // Return same program if underlying program doesnt change
103562         var oldState = oldProgram && oldProgram.getState();
103563         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103564             newProgram = undefined; // TODO: GH#18217
103565             oldState = undefined;
103566             return oldProgram;
103567         }
103568         /**
103569          * Create the canonical file name for identity
103570          */
103571         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103572         /**
103573          * Computing hash to for signature verification
103574          */
103575         var computeHash = host.createHash || ts.generateDjb2Hash;
103576         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103577         var backupState;
103578         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103579         // To ensure that we arent storing any references to old program or new program without state
103580         newProgram = undefined; // TODO: GH#18217
103581         oldProgram = undefined;
103582         oldState = undefined;
103583         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103584         builderProgram.getState = function () { return state; };
103585         builderProgram.backupState = function () {
103586             ts.Debug.assert(backupState === undefined);
103587             backupState = cloneBuilderProgramState(state);
103588         };
103589         builderProgram.restoreState = function () {
103590             state = ts.Debug.checkDefined(backupState);
103591             backupState = undefined;
103592         };
103593         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103594         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103595         builderProgram.emit = emit;
103596         builderProgram.releaseProgram = function () {
103597             releaseCache(state);
103598             backupState = undefined;
103599         };
103600         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103601             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103602         }
103603         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103604             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103605             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103606         }
103607         else {
103608             ts.notImplemented();
103609         }
103610         return builderProgram;
103611         /**
103612          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103613          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103614          * in that order would be used to write the files
103615          */
103616         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103617             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103618             var emitKind = 1 /* Full */;
103619             var isPendingEmitFile = false;
103620             if (!affected) {
103621                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103622                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103623                     if (!pendingAffectedFile) {
103624                         if (state.emittedBuildInfo) {
103625                             return undefined;
103626                         }
103627                         var affected_1 = ts.Debug.checkDefined(state.program);
103628                         return toAffectedFileEmitResult(state, 
103629                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103630                         // Otherwise just affected file
103631                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103632                         /*isPendingEmitFile*/ false, 
103633                         /*isBuildInfoEmit*/ true);
103634                     }
103635                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103636                     isPendingEmitFile = true;
103637                 }
103638                 else {
103639                     var program = ts.Debug.checkDefined(state.program);
103640                     if (state.programEmitComplete)
103641                         return undefined;
103642                     affected = program;
103643                 }
103644             }
103645             return toAffectedFileEmitResult(state, 
103646             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103647             // Otherwise just affected file
103648             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);
103649         }
103650         /**
103651          * Emits the JavaScript and declaration files.
103652          * When targetSource file is specified, emits the files corresponding to that source file,
103653          * otherwise for the whole program.
103654          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103655          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103656          * it will only emit all the affected files instead of whole program
103657          *
103658          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103659          * in that order would be used to write the files
103660          */
103661         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103662             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103663                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103664                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103665                 if (result)
103666                     return result;
103667                 if (!targetSourceFile) {
103668                     // Emit and report any errors we ran into.
103669                     var sourceMaps = [];
103670                     var emitSkipped = false;
103671                     var diagnostics = void 0;
103672                     var emittedFiles = [];
103673                     var affectedEmitResult = void 0;
103674                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103675                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103676                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103677                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103678                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103679                     }
103680                     return {
103681                         emitSkipped: emitSkipped,
103682                         diagnostics: diagnostics || ts.emptyArray,
103683                         emittedFiles: emittedFiles,
103684                         sourceMaps: sourceMaps
103685                     };
103686                 }
103687             }
103688             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103689         }
103690         /**
103691          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103692          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103693          */
103694         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103695             while (true) {
103696                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103697                 if (!affected) {
103698                     // Done
103699                     return undefined;
103700                 }
103701                 else if (affected === state.program) {
103702                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103703                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103704                 }
103705                 // Add file to affected file pending emit to handle for later emit time
103706                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103707                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103708                 }
103709                 // Get diagnostics for the affected file if its not ignored
103710                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103711                     // Get next affected file
103712                     doneWithAffectedFile(state, affected);
103713                     continue;
103714                 }
103715                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103716             }
103717         }
103718         /**
103719          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103720          * The semantic diagnostics are cached and managed here
103721          * Note that it is assumed that when asked about semantic diagnostics through this API,
103722          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103723          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103724          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103725          */
103726         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103727             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103728             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103729             if (compilerOptions.outFile || compilerOptions.out) {
103730                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103731                 // We dont need to cache the diagnostics just return them from program
103732                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103733             }
103734             if (sourceFile) {
103735                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103736             }
103737             // When semantic builder asks for diagnostics of the whole program,
103738             // ensure that all the affected files are handled
103739             // eslint-disable-next-line no-empty
103740             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103741             }
103742             var diagnostics;
103743             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103744                 var sourceFile_1 = _a[_i];
103745                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103746             }
103747             return diagnostics || ts.emptyArray;
103748         }
103749     }
103750     ts.createBuilderProgram = createBuilderProgram;
103751     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103752         if (!state.affectedFilesPendingEmit)
103753             state.affectedFilesPendingEmit = [];
103754         if (!state.affectedFilesPendingEmitKind)
103755             state.affectedFilesPendingEmitKind = ts.createMap();
103756         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103757         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103758         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103759         // affectedFilesPendingEmitIndex === undefined
103760         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103761         //   so start from 0 as array would be affectedFilesPendingEmit
103762         // else, continue to iterate from existing index, the current set is appended to existing files
103763         if (state.affectedFilesPendingEmitIndex === undefined) {
103764             state.affectedFilesPendingEmitIndex = 0;
103765         }
103766     }
103767     function getMapOfReferencedSet(mapLike, toPath) {
103768         if (!mapLike)
103769             return undefined;
103770         var map = ts.createMap();
103771         // Copies keys/values from template. Note that for..in will not throw if
103772         // template is undefined, and instead will just exit the loop.
103773         for (var key in mapLike) {
103774             if (ts.hasProperty(mapLike, key)) {
103775                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103776             }
103777         }
103778         return map;
103779     }
103780     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103781         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103782         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103783         var fileInfos = ts.createMap();
103784         for (var key in program.fileInfos) {
103785             if (ts.hasProperty(program.fileInfos, key)) {
103786                 fileInfos.set(toPath(key), program.fileInfos[key]);
103787             }
103788         }
103789         var state = {
103790             fileInfos: fileInfos,
103791             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103792             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103793             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103794             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]; }),
103795             hasReusableDiagnostic: true
103796         };
103797         return {
103798             getState: function () { return state; },
103799             backupState: ts.noop,
103800             restoreState: ts.noop,
103801             getProgram: ts.notImplemented,
103802             getProgramOrUndefined: ts.returnUndefined,
103803             releaseProgram: ts.noop,
103804             getCompilerOptions: function () { return state.compilerOptions; },
103805             getSourceFile: ts.notImplemented,
103806             getSourceFiles: ts.notImplemented,
103807             getOptionsDiagnostics: ts.notImplemented,
103808             getGlobalDiagnostics: ts.notImplemented,
103809             getConfigFileParsingDiagnostics: ts.notImplemented,
103810             getSyntacticDiagnostics: ts.notImplemented,
103811             getDeclarationDiagnostics: ts.notImplemented,
103812             getSemanticDiagnostics: ts.notImplemented,
103813             emit: ts.notImplemented,
103814             getAllDependencies: ts.notImplemented,
103815             getCurrentDirectory: ts.notImplemented,
103816             emitNextAffectedFile: ts.notImplemented,
103817             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
103818             close: ts.noop,
103819         };
103820         function toPath(path) {
103821             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103822         }
103823         function toAbsolutePath(path) {
103824             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
103825         }
103826     }
103827     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
103828     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
103829         return {
103830             getState: ts.notImplemented,
103831             backupState: ts.noop,
103832             restoreState: ts.noop,
103833             getProgram: getProgram,
103834             getProgramOrUndefined: function () { return state.program; },
103835             releaseProgram: function () { return state.program = undefined; },
103836             getCompilerOptions: function () { return state.compilerOptions; },
103837             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
103838             getSourceFiles: function () { return getProgram().getSourceFiles(); },
103839             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
103840             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
103841             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
103842             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
103843             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
103844             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
103845             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
103846             getAllDependencies: ts.notImplemented,
103847             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
103848             close: ts.noop,
103849         };
103850         function getProgram() {
103851             return ts.Debug.checkDefined(state.program);
103852         }
103853     }
103854     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
103855 })(ts || (ts = {}));
103856 var ts;
103857 (function (ts) {
103858     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103859         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103860     }
103861     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
103862     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103863         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103864     }
103865     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
103866     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103867         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103868         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
103869     }
103870     ts.createAbstractBuilder = createAbstractBuilder;
103871 })(ts || (ts = {}));
103872 /*@internal*/
103873 var ts;
103874 (function (ts) {
103875     function removeIgnoredPath(path) {
103876         // Consider whole staging folder as if node_modules changed.
103877         if (ts.endsWith(path, "/node_modules/.staging")) {
103878             return ts.removeSuffix(path, "/.staging");
103879         }
103880         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
103881             undefined :
103882             path;
103883     }
103884     ts.removeIgnoredPath = removeIgnoredPath;
103885     /**
103886      * Filter out paths like
103887      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
103888      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
103889      * @param dirPath
103890      */
103891     function canWatchDirectory(dirPath) {
103892         var rootLength = ts.getRootLength(dirPath);
103893         if (dirPath.length === rootLength) {
103894             // Ignore "/", "c:/"
103895             return false;
103896         }
103897         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
103898         if (nextDirectorySeparator === -1) {
103899             // ignore "/user", "c:/users" or "c:/folderAtRoot"
103900             return false;
103901         }
103902         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
103903         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
103904         if (isNonDirectorySeparatorRoot &&
103905             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
103906             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
103907             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
103908             if (nextDirectorySeparator === -1) {
103909                 // ignore "//vda1cs4850/c$/folderAtRoot"
103910                 return false;
103911             }
103912             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
103913         }
103914         if (isNonDirectorySeparatorRoot &&
103915             pathPartForUserCheck.search(/users\//i) !== 0) {
103916             // Paths like c:/folderAtRoot/subFolder are allowed
103917             return true;
103918         }
103919         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
103920             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
103921             if (searchIndex === 0) {
103922                 // Folder isnt at expected minimum levels
103923                 return false;
103924             }
103925         }
103926         return true;
103927     }
103928     ts.canWatchDirectory = canWatchDirectory;
103929     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
103930         var filesWithChangedSetOfUnresolvedImports;
103931         var filesWithInvalidatedResolutions;
103932         var filesWithInvalidatedNonRelativeUnresolvedImports;
103933         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
103934         var resolutionsWithFailedLookups = [];
103935         var resolvedFileToResolution = ts.createMultiMap();
103936         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
103937         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
103938         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
103939         // The key in the map is source file's path.
103940         // The values are Map of resolutions with key being name lookedup.
103941         var resolvedModuleNames = ts.createMap();
103942         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
103943         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
103944         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
103945         var resolvedTypeReferenceDirectives = ts.createMap();
103946         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
103947         /**
103948          * These are the extensions that failed lookup files will have by default,
103949          * any other extension of failed lookup will be store that path in custom failed lookup path
103950          * This helps in not having to comb through all resolutions when files are added/removed
103951          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
103952          */
103953         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
103954         var customFailedLookupPaths = ts.createMap();
103955         var directoryWatchesOfFailedLookups = ts.createMap();
103956         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
103957         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
103958         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
103959         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
103960         var typeRootsWatches = ts.createMap();
103961         return {
103962             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
103963             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
103964             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
103965             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
103966             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
103967             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
103968             resolveModuleNames: resolveModuleNames,
103969             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
103970             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
103971             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
103972             removeResolutionsOfFile: removeResolutionsOfFile,
103973             invalidateResolutionOfFile: invalidateResolutionOfFile,
103974             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
103975             createHasInvalidatedResolution: createHasInvalidatedResolution,
103976             updateTypeRootsWatch: updateTypeRootsWatch,
103977             closeTypeRootsWatch: closeTypeRootsWatch,
103978             clear: clear
103979         };
103980         function getResolvedModule(resolution) {
103981             return resolution.resolvedModule;
103982         }
103983         function getResolvedTypeReferenceDirective(resolution) {
103984             return resolution.resolvedTypeReferenceDirective;
103985         }
103986         function isInDirectoryPath(dir, file) {
103987             if (dir === undefined || file.length <= dir.length) {
103988                 return false;
103989             }
103990             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
103991         }
103992         function clear() {
103993             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
103994             customFailedLookupPaths.clear();
103995             nonRelativeExternalModuleResolutions.clear();
103996             closeTypeRootsWatch();
103997             resolvedModuleNames.clear();
103998             resolvedTypeReferenceDirectives.clear();
103999             resolvedFileToResolution.clear();
104000             resolutionsWithFailedLookups.length = 0;
104001             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104002             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104003             clearPerDirectoryResolutions();
104004         }
104005         function startRecordingFilesWithChangedResolutions() {
104006             filesWithChangedSetOfUnresolvedImports = [];
104007         }
104008         function finishRecordingFilesWithChangedResolutions() {
104009             var collected = filesWithChangedSetOfUnresolvedImports;
104010             filesWithChangedSetOfUnresolvedImports = undefined;
104011             return collected;
104012         }
104013         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104014             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104015                 return false;
104016             }
104017             // Invalidated if file has unresolved imports
104018             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104019             return !!value && !!value.length;
104020         }
104021         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104022             if (forceAllFilesAsInvalidated) {
104023                 // Any file asked would have invalidated resolution
104024                 filesWithInvalidatedResolutions = undefined;
104025                 return ts.returnTrue;
104026             }
104027             var collected = filesWithInvalidatedResolutions;
104028             filesWithInvalidatedResolutions = undefined;
104029             return function (path) { return (!!collected && collected.has(path)) ||
104030                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104031         }
104032         function clearPerDirectoryResolutions() {
104033             perDirectoryResolvedModuleNames.clear();
104034             nonRelativeModuleNameCache.clear();
104035             perDirectoryResolvedTypeReferenceDirectives.clear();
104036             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104037             nonRelativeExternalModuleResolutions.clear();
104038         }
104039         function finishCachingPerDirectoryResolution() {
104040             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104041             clearPerDirectoryResolutions();
104042             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104043                 if (watcher.refCount === 0) {
104044                     directoryWatchesOfFailedLookups.delete(path);
104045                     watcher.watcher.close();
104046                 }
104047             });
104048         }
104049         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104050             var _a;
104051             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104052             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104053             if (!resolutionHost.getGlobalCache) {
104054                 return primaryResult;
104055             }
104056             // otherwise try to load typings from @types
104057             var globalCache = resolutionHost.getGlobalCache();
104058             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104059                 // create different collection of failed lookup locations for second pass
104060                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104061                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104062                 if (resolvedModule) {
104063                     // Modify existing resolution so its saved in the directory cache as well
104064                     primaryResult.resolvedModule = resolvedModule;
104065                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104066                     return primaryResult;
104067                 }
104068             }
104069             // Default return the result from the first pass
104070             return primaryResult;
104071         }
104072         function resolveNamesWithLocalCache(_a) {
104073             var _b;
104074             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;
104075             var path = resolutionHost.toPath(containingFile);
104076             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104077             var dirPath = ts.getDirectoryPath(path);
104078             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104079             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104080             if (!perDirectoryResolution) {
104081                 perDirectoryResolution = ts.createMap();
104082                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104083             }
104084             var resolvedModules = [];
104085             var compilerOptions = resolutionHost.getCompilationSettings();
104086             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104087             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104088             var program = resolutionHost.getCurrentProgram();
104089             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104090             var unmatchedRedirects = oldRedirect ?
104091                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104092                 !!redirectedReference;
104093             var seenNamesInFile = ts.createMap();
104094             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104095                 var name = names_3[_i];
104096                 var resolution = resolutionsInFile.get(name);
104097                 // Resolution is valid if it is present and not invalidated
104098                 if (!seenNamesInFile.has(name) &&
104099                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104100                     // If the name is unresolved import that was invalidated, recalculate
104101                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104102                     var existingResolution = resolution;
104103                     var resolutionInDirectory = perDirectoryResolution.get(name);
104104                     if (resolutionInDirectory) {
104105                         resolution = resolutionInDirectory;
104106                     }
104107                     else {
104108                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104109                         perDirectoryResolution.set(name, resolution);
104110                     }
104111                     resolutionsInFile.set(name, resolution);
104112                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104113                     if (existingResolution) {
104114                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104115                     }
104116                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104117                         filesWithChangedSetOfUnresolvedImports.push(path);
104118                         // reset log changes to avoid recording the same file multiple times
104119                         logChanges = false;
104120                     }
104121                 }
104122                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104123                 seenNamesInFile.set(name, true);
104124                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104125             }
104126             // Stop watching and remove the unused name
104127             resolutionsInFile.forEach(function (resolution, name) {
104128                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104129                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104130                     resolutionsInFile.delete(name);
104131                 }
104132             });
104133             return resolvedModules;
104134             function resolutionIsEqualTo(oldResolution, newResolution) {
104135                 if (oldResolution === newResolution) {
104136                     return true;
104137                 }
104138                 if (!oldResolution || !newResolution) {
104139                     return false;
104140                 }
104141                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104142                 var newResult = getResolutionWithResolvedFileName(newResolution);
104143                 if (oldResult === newResult) {
104144                     return true;
104145                 }
104146                 if (!oldResult || !newResult) {
104147                     return false;
104148                 }
104149                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104150             }
104151         }
104152         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104153             return resolveNamesWithLocalCache({
104154                 names: typeDirectiveNames,
104155                 containingFile: containingFile,
104156                 redirectedReference: redirectedReference,
104157                 cache: resolvedTypeReferenceDirectives,
104158                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104159                 loader: ts.resolveTypeReferenceDirective,
104160                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104161                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104162             });
104163         }
104164         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104165             return resolveNamesWithLocalCache({
104166                 names: moduleNames,
104167                 containingFile: containingFile,
104168                 redirectedReference: redirectedReference,
104169                 cache: resolvedModuleNames,
104170                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104171                 loader: resolveModuleName,
104172                 getResolutionWithResolvedFileName: getResolvedModule,
104173                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104174                 reusedNames: reusedNames,
104175                 logChanges: logChangesWhenResolvingModule
104176             });
104177         }
104178         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104179             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104180             return cache && cache.get(moduleName);
104181         }
104182         function isNodeModulesAtTypesDirectory(dirPath) {
104183             return ts.endsWith(dirPath, "/node_modules/@types");
104184         }
104185         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104186             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104187                 // Ensure failed look up is normalized path
104188                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104189                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104190                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104191                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104192                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104193                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104194                     return {
104195                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104196                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104197                     };
104198                 }
104199                 else {
104200                     // Always watch root directory non recursively
104201                     return {
104202                         dir: rootDir,
104203                         dirPath: rootPath,
104204                         nonRecursive: false
104205                     };
104206                 }
104207             }
104208             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104209         }
104210         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104211             // If directory path contains node module, get the most parent node_modules directory for watching
104212             while (ts.pathContainsNodeModules(dirPath)) {
104213                 dir = ts.getDirectoryPath(dir);
104214                 dirPath = ts.getDirectoryPath(dirPath);
104215             }
104216             // If the directory is node_modules use it to watch, always watch it recursively
104217             if (ts.isNodeModulesDirectory(dirPath)) {
104218                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104219             }
104220             var nonRecursive = true;
104221             // Use some ancestor of the root directory
104222             var subDirectoryPath, subDirectory;
104223             if (rootPath !== undefined) {
104224                 while (!isInDirectoryPath(dirPath, rootPath)) {
104225                     var parentPath = ts.getDirectoryPath(dirPath);
104226                     if (parentPath === dirPath) {
104227                         break;
104228                     }
104229                     nonRecursive = false;
104230                     subDirectoryPath = dirPath;
104231                     subDirectory = dir;
104232                     dirPath = parentPath;
104233                     dir = ts.getDirectoryPath(dir);
104234                 }
104235             }
104236             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104237         }
104238         function isPathWithDefaultFailedLookupExtension(path) {
104239             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104240         }
104241         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104242             if (resolution.refCount) {
104243                 resolution.refCount++;
104244                 ts.Debug.assertDefined(resolution.files);
104245             }
104246             else {
104247                 resolution.refCount = 1;
104248                 ts.Debug.assert(resolution.files === undefined);
104249                 if (ts.isExternalModuleNameRelative(name)) {
104250                     watchFailedLookupLocationOfResolution(resolution);
104251                 }
104252                 else {
104253                     nonRelativeExternalModuleResolutions.add(name, resolution);
104254                 }
104255                 var resolved = getResolutionWithResolvedFileName(resolution);
104256                 if (resolved && resolved.resolvedFileName) {
104257                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104258                 }
104259             }
104260             (resolution.files || (resolution.files = [])).push(filePath);
104261         }
104262         function watchFailedLookupLocationOfResolution(resolution) {
104263             ts.Debug.assert(!!resolution.refCount);
104264             var failedLookupLocations = resolution.failedLookupLocations;
104265             if (!failedLookupLocations.length)
104266                 return;
104267             resolutionsWithFailedLookups.push(resolution);
104268             var setAtRoot = false;
104269             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104270                 var failedLookupLocation = failedLookupLocations_1[_i];
104271                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104272                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104273                 if (toWatch) {
104274                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104275                     // If the failed lookup location path is not one of the supported extensions,
104276                     // store it in the custom path
104277                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104278                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104279                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104280                     }
104281                     if (dirPath === rootPath) {
104282                         ts.Debug.assert(!nonRecursive);
104283                         setAtRoot = true;
104284                     }
104285                     else {
104286                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104287                     }
104288                 }
104289             }
104290             if (setAtRoot) {
104291                 // This is always non recursive
104292                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104293             }
104294         }
104295         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104296             var program = resolutionHost.getCurrentProgram();
104297             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104298                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104299             }
104300         }
104301         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104302             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104303             if (dirWatcher) {
104304                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104305                 dirWatcher.refCount++;
104306             }
104307             else {
104308                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104309             }
104310         }
104311         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104312             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104313             resolution.refCount--;
104314             if (resolution.refCount) {
104315                 return;
104316             }
104317             var resolved = getResolutionWithResolvedFileName(resolution);
104318             if (resolved && resolved.resolvedFileName) {
104319                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104320             }
104321             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104322                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104323                 return;
104324             }
104325             var failedLookupLocations = resolution.failedLookupLocations;
104326             var removeAtRoot = false;
104327             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104328                 var failedLookupLocation = failedLookupLocations_2[_i];
104329                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104330                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104331                 if (toWatch) {
104332                     var dirPath = toWatch.dirPath;
104333                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104334                     if (refCount) {
104335                         if (refCount === 1) {
104336                             customFailedLookupPaths.delete(failedLookupLocationPath);
104337                         }
104338                         else {
104339                             ts.Debug.assert(refCount > 1);
104340                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104341                         }
104342                     }
104343                     if (dirPath === rootPath) {
104344                         removeAtRoot = true;
104345                     }
104346                     else {
104347                         removeDirectoryWatcher(dirPath);
104348                     }
104349                 }
104350             }
104351             if (removeAtRoot) {
104352                 removeDirectoryWatcher(rootPath);
104353             }
104354         }
104355         function removeDirectoryWatcher(dirPath) {
104356             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104357             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104358             dirWatcher.refCount--;
104359         }
104360         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104361             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104362                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104363                 if (cachedDirectoryStructureHost) {
104364                     // Since the file existence changed, update the sourceFiles cache
104365                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104366                 }
104367                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104368                     resolutionHost.onInvalidatedResolution();
104369                 }
104370             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104371         }
104372         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104373             // Deleted file, stop watching failed lookups for all the resolutions in the file
104374             var resolutions = cache.get(filePath);
104375             if (resolutions) {
104376                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104377                 cache.delete(filePath);
104378             }
104379         }
104380         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104381             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104382                 return;
104383             }
104384             var program = resolutionHost.getCurrentProgram();
104385             if (!program) {
104386                 return;
104387             }
104388             // If this file is input file for the referenced project, get it
104389             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104390             if (!resolvedProjectReference) {
104391                 return;
104392             }
104393             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104394             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104395         }
104396         function removeResolutionsOfFile(filePath) {
104397             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104398             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104399         }
104400         function invalidateResolution(resolution) {
104401             resolution.isInvalidated = true;
104402             var changedInAutoTypeReferenced = false;
104403             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104404                 var containingFilePath = _a[_i];
104405                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104406                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104407                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104408             }
104409             if (changedInAutoTypeReferenced) {
104410                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104411             }
104412         }
104413         function invalidateResolutionOfFile(filePath) {
104414             removeResolutionsOfFile(filePath);
104415             // Resolution is invalidated if the resulting file name is same as the deleted file path
104416             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104417         }
104418         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104419             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104420             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104421         }
104422         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104423             var isChangedFailedLookupLocation;
104424             if (isCreatingWatchedDirectory) {
104425                 // Watching directory is created
104426                 // Invalidate any resolution has failed lookup in this directory
104427                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104428             }
104429             else {
104430                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104431                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104432                 if (!updatedPath)
104433                     return false;
104434                 fileOrDirectoryPath = updatedPath;
104435                 // prevent saving an open file from over-eagerly triggering invalidation
104436                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104437                     return false;
104438                 }
104439                 // Some file or directory in the watching directory is created
104440                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104441                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104442                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104443                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104444                     // Invalidate any resolution from this directory
104445                     isChangedFailedLookupLocation = function (location) {
104446                         var locationPath = resolutionHost.toPath(location);
104447                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104448                     };
104449                 }
104450                 else {
104451                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104452                         return false;
104453                     }
104454                     // Ignore emits from the program
104455                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104456                         return false;
104457                     }
104458                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104459                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104460                 }
104461             }
104462             var invalidated = false;
104463             // Resolution is invalidated if the resulting file name is same as the deleted file path
104464             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104465                 var resolution = resolutionsWithFailedLookups_1[_i];
104466                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104467                     invalidateResolution(resolution);
104468                     invalidated = true;
104469                 }
104470             }
104471             return invalidated;
104472         }
104473         function closeTypeRootsWatch() {
104474             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104475         }
104476         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104477             if (isInDirectoryPath(rootPath, typeRootPath)) {
104478                 return rootPath;
104479             }
104480             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104481             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104482         }
104483         function createTypeRootsWatch(typeRootPath, typeRoot) {
104484             // Create new watch and recursive info
104485             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104486                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104487                 if (cachedDirectoryStructureHost) {
104488                     // Since the file existence changed, update the sourceFiles cache
104489                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104490                 }
104491                 // For now just recompile
104492                 // We could potentially store more data here about whether it was/would be really be used or not
104493                 // and with that determine to trigger compilation but for now this is enough
104494                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104495                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104496                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104497                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104498                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104499                     resolutionHost.onInvalidatedResolution();
104500                 }
104501             }, 1 /* Recursive */);
104502         }
104503         /**
104504          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104505          * To be called when compiler options change
104506          */
104507         function updateTypeRootsWatch() {
104508             var options = resolutionHost.getCompilationSettings();
104509             if (options.types) {
104510                 // No need to do any watch since resolution cache is going to handle the failed lookups
104511                 // for the types added by this
104512                 closeTypeRootsWatch();
104513                 return;
104514             }
104515             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104516             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104517             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104518             if (typeRoots) {
104519                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104520                     createNewValue: createTypeRootsWatch,
104521                     onDeleteValue: ts.closeFileWatcher
104522                 });
104523             }
104524             else {
104525                 closeTypeRootsWatch();
104526             }
104527         }
104528         /**
104529          * Use this function to return if directory exists to get type roots to watch
104530          * If we return directory exists then only the paths will be added to type roots
104531          * Hence return true for all directories except root directories which are filtered from watching
104532          */
104533         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104534             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104535             var dirPath = resolutionHost.toPath(dir);
104536             return dirPath === rootPath || canWatchDirectory(dirPath);
104537         }
104538     }
104539     ts.createResolutionCache = createResolutionCache;
104540 })(ts || (ts = {}));
104541 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104542 /* @internal */
104543 var ts;
104544 (function (ts) {
104545     var moduleSpecifiers;
104546     (function (moduleSpecifiers) {
104547         var RelativePreference;
104548         (function (RelativePreference) {
104549             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104550             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104551             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104552         })(RelativePreference || (RelativePreference = {}));
104553         // See UserPreferences#importPathEnding
104554         var Ending;
104555         (function (Ending) {
104556             Ending[Ending["Minimal"] = 0] = "Minimal";
104557             Ending[Ending["Index"] = 1] = "Index";
104558             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104559         })(Ending || (Ending = {}));
104560         function getPreferences(_a, compilerOptions, importingSourceFile) {
104561             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104562             return {
104563                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104564                 ending: getEnding(),
104565             };
104566             function getEnding() {
104567                 switch (importModuleSpecifierEnding) {
104568                     case "minimal": return 0 /* Minimal */;
104569                     case "index": return 1 /* Index */;
104570                     case "js": return 2 /* JsExtension */;
104571                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104572                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104573                 }
104574             }
104575         }
104576         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104577             return {
104578                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104579                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104580                     2 /* JsExtension */ :
104581                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104582             };
104583         }
104584         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104585             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104586             if (res === oldImportSpecifier)
104587                 return undefined;
104588             return res;
104589         }
104590         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104591         // Note: importingSourceFile is just for usesJsExtensionOnImports
104592         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104593             if (preferences === void 0) { preferences = {}; }
104594             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104595         }
104596         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104597         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104598             var info = getInfo(importingSourceFileName, host);
104599             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104600             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104601         }
104602         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104603         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104604             var info = getInfo(importingSourceFileName, host);
104605             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104606             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104607                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104608         }
104609         /** Returns an import for each symlink and for the realpath. */
104610         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104611             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104612             if (ambient)
104613                 return [ambient];
104614             var info = getInfo(importingSourceFile.path, host);
104615             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104616             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104617             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104618             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104619             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104620         }
104621         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104622         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104623         function getInfo(importingSourceFileName, host) {
104624             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104625             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104626             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104627         }
104628         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104629             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104630             var ending = _b.ending, relativePreference = _b.relativePreference;
104631             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104632             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104633                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104634             if (!baseUrl || relativePreference === 0 /* Relative */) {
104635                 return relativePath;
104636             }
104637             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104638             if (!relativeToBaseUrl) {
104639                 return relativePath;
104640             }
104641             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104642             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104643             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104644             if (relativePreference === 1 /* NonRelative */) {
104645                 return nonRelative;
104646             }
104647             if (relativePreference !== 2 /* Auto */)
104648                 ts.Debug.assertNever(relativePreference);
104649             // Prefer a relative import over a baseUrl import if it has fewer components.
104650             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104651         }
104652         function countPathComponents(path) {
104653             var count = 0;
104654             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104655                 if (path.charCodeAt(i) === 47 /* slash */)
104656                     count++;
104657             }
104658             return count;
104659         }
104660         moduleSpecifiers.countPathComponents = countPathComponents;
104661         function usesJsExtensionOnImports(_a) {
104662             var imports = _a.imports;
104663             return ts.firstDefined(imports, function (_a) {
104664                 var text = _a.text;
104665                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104666             }) || false;
104667         }
104668         function numberOfDirectorySeparators(str) {
104669             var match = str.match(/\//g);
104670             return match ? match.length : 0;
104671         }
104672         function comparePathsByNumberOfDirectorySeparators(a, b) {
104673             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104674         }
104675         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104676             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104677             var cwd = host.getCurrentDirectory();
104678             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104679             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104680             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104681             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104682             if (!preferSymlinks) {
104683                 var result_12 = ts.forEach(targets, cb);
104684                 if (result_12)
104685                     return result_12;
104686             }
104687             var links = host.getProbableSymlinks
104688                 ? host.getProbableSymlinks(host.getSourceFiles())
104689                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104690             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104691             var result = ts.forEachEntry(links, function (resolved, path) {
104692                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104693                     return undefined; // Don't want to a package to globally import from itself
104694                 }
104695                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104696                 if (target === undefined)
104697                     return undefined;
104698                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104699                 var option = ts.resolvePath(path, relative);
104700                 if (!host.fileExists || host.fileExists(option)) {
104701                     var result_13 = cb(option);
104702                     if (result_13)
104703                         return result_13;
104704                 }
104705             });
104706             return result ||
104707                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104708         }
104709         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104710         /**
104711          * Looks for existing imports that use symlinks to this module.
104712          * Symlinks will be returned first so they are preferred over the real path.
104713          */
104714         function getAllModulePaths(importingFileName, importedFileName, host) {
104715             var cwd = host.getCurrentDirectory();
104716             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104717             var allFileNames = ts.createMap();
104718             var importedFileFromNodeModules = false;
104719             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104720             /*preferSymlinks*/ true, function (path) {
104721                 // dont return value, so we collect everything
104722                 allFileNames.set(path, getCanonicalFileName(path));
104723                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104724             });
104725             // Sort by paths closest to importing file Name directory
104726             var sortedPaths = [];
104727             var _loop_20 = function (directory) {
104728                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104729                 var pathsInDirectory;
104730                 allFileNames.forEach(function (canonicalFileName, fileName) {
104731                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104732                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104733                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104734                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104735                         }
104736                         allFileNames.delete(fileName);
104737                     }
104738                 });
104739                 if (pathsInDirectory) {
104740                     if (pathsInDirectory.length > 1) {
104741                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104742                     }
104743                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104744                 }
104745                 var newDirectory = ts.getDirectoryPath(directory);
104746                 if (newDirectory === directory)
104747                     return out_directory_1 = directory, "break";
104748                 directory = newDirectory;
104749                 out_directory_1 = directory;
104750             };
104751             var out_directory_1;
104752             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104753                 var state_8 = _loop_20(directory);
104754                 directory = out_directory_1;
104755                 if (state_8 === "break")
104756                     break;
104757             }
104758             if (allFileNames.size) {
104759                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104760                 if (remainingPaths.length > 1)
104761                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104762                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104763             }
104764             return sortedPaths;
104765         }
104766         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104767             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104768             if (decl) {
104769                 return decl.name.text;
104770             }
104771         }
104772         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104773             for (var key in paths) {
104774                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104775                     var patternText_1 = _a[_i];
104776                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104777                     var indexOfStar = pattern.indexOf("*");
104778                     if (indexOfStar !== -1) {
104779                         var prefix = pattern.substr(0, indexOfStar);
104780                         var suffix = pattern.substr(indexOfStar + 1);
104781                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104782                             ts.startsWith(relativeToBaseUrl, prefix) &&
104783                             ts.endsWith(relativeToBaseUrl, suffix) ||
104784                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104785                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104786                             return key.replace("*", matchedStar);
104787                         }
104788                     }
104789                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104790                         return key;
104791                     }
104792                 }
104793             }
104794         }
104795         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104796             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104797             if (normalizedTargetPath === undefined) {
104798                 return undefined;
104799             }
104800             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104801             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104802             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104803                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104804                 : ts.removeFileExtension(relativePath);
104805         }
104806         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104807             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104808             if (!host.fileExists || !host.readFile) {
104809                 return undefined;
104810             }
104811             var parts = getNodeModulePathParts(moduleFileName);
104812             if (!parts) {
104813                 return undefined;
104814             }
104815             // Simplify the full file path to something that can be resolved by Node.
104816             var moduleSpecifier = moduleFileName;
104817             if (!packageNameOnly) {
104818                 var packageRootIndex = parts.packageRootIndex;
104819                 var moduleFileNameForExtensionless = void 0;
104820                 while (true) {
104821                     // If the module could be imported by a directory name, use that directory's name
104822                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
104823                     if (packageRootPath) {
104824                         moduleSpecifier = packageRootPath;
104825                         break;
104826                     }
104827                     if (!moduleFileNameForExtensionless)
104828                         moduleFileNameForExtensionless = moduleFileToTry;
104829                     // try with next level of directory
104830                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
104831                     if (packageRootIndex === -1) {
104832                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
104833                         break;
104834                     }
104835                 }
104836             }
104837             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
104838             // Get a path that's relative to node_modules or the importing file's path
104839             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
104840             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
104841             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
104842                 return undefined;
104843             }
104844             // If the module was found in @types, get the actual Node package name
104845             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
104846             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
104847             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
104848             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
104849             function tryDirectoryWithPackageJson(packageRootIndex) {
104850                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
104851                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
104852                 var moduleFileToTry = moduleFileName;
104853                 if (host.fileExists(packageJsonPath)) {
104854                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
104855                     var versionPaths = packageJsonContent.typesVersions
104856                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
104857                         : undefined;
104858                     if (versionPaths) {
104859                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
104860                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
104861                         if (fromPaths !== undefined) {
104862                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
104863                         }
104864                     }
104865                     // If the file is the main module, it can be imported by the package name
104866                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
104867                     if (ts.isString(mainFileRelative)) {
104868                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
104869                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
104870                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
104871                         }
104872                     }
104873                 }
104874                 return { moduleFileToTry: moduleFileToTry };
104875             }
104876             function getExtensionlessFileName(path) {
104877                 // We still have a file name - remove the extension
104878                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
104879                 // If the file is /index, it can be imported by its directory name
104880                 // IFF there is not _also_ a file by the same name
104881                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
104882                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
104883                 }
104884                 return fullModulePathWithoutExtension;
104885             }
104886         }
104887         function tryGetAnyFileFromPath(host, path) {
104888             if (!host.fileExists)
104889                 return;
104890             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
104891             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
104892             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
104893                 var e = extensions_3[_i];
104894                 var fullPath = path + e;
104895                 if (host.fileExists(fullPath)) {
104896                     return fullPath;
104897                 }
104898             }
104899         }
104900         function getNodeModulePathParts(fullPath) {
104901             // If fullPath can't be valid module file within node_modules, returns undefined.
104902             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
104903             // Returns indices:                       ^            ^                                                      ^             ^
104904             var topLevelNodeModulesIndex = 0;
104905             var topLevelPackageNameIndex = 0;
104906             var packageRootIndex = 0;
104907             var fileNameIndex = 0;
104908             var States;
104909             (function (States) {
104910                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
104911                 States[States["NodeModules"] = 1] = "NodeModules";
104912                 States[States["Scope"] = 2] = "Scope";
104913                 States[States["PackageContent"] = 3] = "PackageContent";
104914             })(States || (States = {}));
104915             var partStart = 0;
104916             var partEnd = 0;
104917             var state = 0 /* BeforeNodeModules */;
104918             while (partEnd >= 0) {
104919                 partStart = partEnd;
104920                 partEnd = fullPath.indexOf("/", partStart + 1);
104921                 switch (state) {
104922                     case 0 /* BeforeNodeModules */:
104923                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104924                             topLevelNodeModulesIndex = partStart;
104925                             topLevelPackageNameIndex = partEnd;
104926                             state = 1 /* NodeModules */;
104927                         }
104928                         break;
104929                     case 1 /* NodeModules */:
104930                     case 2 /* Scope */:
104931                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
104932                             state = 2 /* Scope */;
104933                         }
104934                         else {
104935                             packageRootIndex = partEnd;
104936                             state = 3 /* PackageContent */;
104937                         }
104938                         break;
104939                     case 3 /* PackageContent */:
104940                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104941                             state = 1 /* NodeModules */;
104942                         }
104943                         else {
104944                             state = 3 /* PackageContent */;
104945                         }
104946                         break;
104947                 }
104948             }
104949             fileNameIndex = partStart;
104950             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
104951         }
104952         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
104953             return ts.firstDefined(rootDirs, function (rootDir) {
104954                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
104955                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
104956             });
104957         }
104958         function removeExtensionAndIndexPostFix(fileName, ending, options) {
104959             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
104960                 return fileName;
104961             var noExtension = ts.removeFileExtension(fileName);
104962             switch (ending) {
104963                 case 0 /* Minimal */:
104964                     return ts.removeSuffix(noExtension, "/index");
104965                 case 1 /* Index */:
104966                     return noExtension;
104967                 case 2 /* JsExtension */:
104968                     return noExtension + getJSExtensionForFile(fileName, options);
104969                 default:
104970                     return ts.Debug.assertNever(ending);
104971             }
104972         }
104973         function getJSExtensionForFile(fileName, options) {
104974             var ext = ts.extensionFromPath(fileName);
104975             switch (ext) {
104976                 case ".ts" /* Ts */:
104977                 case ".d.ts" /* Dts */:
104978                     return ".js" /* Js */;
104979                 case ".tsx" /* Tsx */:
104980                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
104981                 case ".js" /* Js */:
104982                 case ".jsx" /* Jsx */:
104983                 case ".json" /* Json */:
104984                     return ext;
104985                 case ".tsbuildinfo" /* TsBuildInfo */:
104986                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
104987                 default:
104988                     return ts.Debug.assertNever(ext);
104989             }
104990         }
104991         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
104992             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
104993             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
104994         }
104995         function isPathRelativeToParent(path) {
104996             return ts.startsWith(path, "..");
104997         }
104998     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
104999 })(ts || (ts = {}));
105000 /*@internal*/
105001 var ts;
105002 (function (ts) {
105003     var sysFormatDiagnosticsHost = ts.sys ? {
105004         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105005         getNewLine: function () { return ts.sys.newLine; },
105006         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105007     } : undefined; // TODO: GH#18217
105008     /**
105009      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105010      */
105011     function createDiagnosticReporter(system, pretty) {
105012         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105013             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105014             getNewLine: function () { return system.newLine; },
105015             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105016         };
105017         if (!pretty) {
105018             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105019         }
105020         var diagnostics = new Array(1);
105021         return function (diagnostic) {
105022             diagnostics[0] = diagnostic;
105023             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105024             diagnostics[0] = undefined; // TODO: GH#18217
105025         };
105026     }
105027     ts.createDiagnosticReporter = createDiagnosticReporter;
105028     /**
105029      * @returns Whether the screen was cleared.
105030      */
105031     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105032         if (system.clearScreen &&
105033             !options.preserveWatchOutput &&
105034             !options.extendedDiagnostics &&
105035             !options.diagnostics &&
105036             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105037             system.clearScreen();
105038             return true;
105039         }
105040         return false;
105041     }
105042     ts.screenStartingMessageCodes = [
105043         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105044         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105045     ];
105046     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105047         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105048             ? newLine + newLine
105049             : newLine;
105050     }
105051     /**
105052      * Get locale specific time based on whether we are in test mode
105053      */
105054     function getLocaleTimeString(system) {
105055         return !system.now ?
105056             new Date().toLocaleTimeString() :
105057             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105058     }
105059     ts.getLocaleTimeString = getLocaleTimeString;
105060     /**
105061      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105062      */
105063     function createWatchStatusReporter(system, pretty) {
105064         return pretty ?
105065             function (diagnostic, newLine, options) {
105066                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105067                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105068                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105069                 system.write(output);
105070             } :
105071             function (diagnostic, newLine, options) {
105072                 var output = "";
105073                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105074                     output += newLine;
105075                 }
105076                 output += getLocaleTimeString(system) + " - ";
105077                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105078                 system.write(output);
105079             };
105080     }
105081     ts.createWatchStatusReporter = createWatchStatusReporter;
105082     /** Parses config file using System interface */
105083     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105084         var host = system;
105085         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105086         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105087         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105088         return result;
105089     }
105090     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105091     function getErrorCountForSummary(diagnostics) {
105092         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105093     }
105094     ts.getErrorCountForSummary = getErrorCountForSummary;
105095     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105096         return errorCount === 1 ?
105097             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105098             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105099     }
105100     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105101     function getErrorSummaryText(errorCount, newLine) {
105102         if (errorCount === 0)
105103             return "";
105104         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105105         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105106     }
105107     ts.getErrorSummaryText = getErrorSummaryText;
105108     function listFiles(program, writeFileName) {
105109         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105110             ts.forEach(program.getSourceFiles(), function (file) {
105111                 writeFileName(file.fileName);
105112             });
105113         }
105114     }
105115     ts.listFiles = listFiles;
105116     /**
105117      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105118      */
105119     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105120         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105121         // First get and report any syntactic errors.
105122         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105123         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105124         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105125         // If we didn't have any syntactic errors, then also try getting the global and
105126         // semantic errors.
105127         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105128             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105129             if (!isListFilesOnly) {
105130                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105131                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105132                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105133                 }
105134             }
105135         }
105136         // Emit and report any errors we ran into.
105137         var emitResult = isListFilesOnly
105138             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105139             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105140         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105141         ts.addRange(allDiagnostics, emitDiagnostics);
105142         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105143         diagnostics.forEach(reportDiagnostic);
105144         if (writeFileName) {
105145             var currentDir_1 = program.getCurrentDirectory();
105146             ts.forEach(emittedFiles, function (file) {
105147                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105148                 writeFileName("TSFILE: " + filepath);
105149             });
105150             listFiles(program, writeFileName);
105151         }
105152         if (reportSummary) {
105153             reportSummary(getErrorCountForSummary(diagnostics));
105154         }
105155         return {
105156             emitResult: emitResult,
105157             diagnostics: diagnostics,
105158         };
105159     }
105160     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105161     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105162         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105163         if (emitResult.emitSkipped && diagnostics.length > 0) {
105164             // If the emitter didn't emit anything, then pass that value along.
105165             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105166         }
105167         else if (diagnostics.length > 0) {
105168             // The emitter emitted something, inform the caller if that happened in the presence
105169             // of diagnostics or not.
105170             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105171         }
105172         return ts.ExitStatus.Success;
105173     }
105174     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105175     ts.noopFileWatcher = { close: ts.noop };
105176     function createWatchHost(system, reportWatchStatus) {
105177         if (system === void 0) { system = ts.sys; }
105178         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105179         return {
105180             onWatchStatusChange: onWatchStatusChange,
105181             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105182             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105183             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105184             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105185         };
105186     }
105187     ts.createWatchHost = createWatchHost;
105188     ts.WatchType = {
105189         ConfigFile: "Config file",
105190         SourceFile: "Source file",
105191         MissingFile: "Missing file",
105192         WildcardDirectory: "Wild card directory",
105193         FailedLookupLocations: "Failed Lookup Locations",
105194         TypeRoots: "Type roots"
105195     };
105196     function createWatchFactory(host, options) {
105197         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105198         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105199         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105200         result.writeLog = writeLog;
105201         return result;
105202     }
105203     ts.createWatchFactory = createWatchFactory;
105204     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105205         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105206         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105207         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105208         return {
105209             getSourceFile: function (fileName, languageVersion, onError) {
105210                 var text;
105211                 try {
105212                     ts.performance.mark("beforeIORead");
105213                     text = host.readFile(fileName, getCompilerOptions().charset);
105214                     ts.performance.mark("afterIORead");
105215                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105216                 }
105217                 catch (e) {
105218                     if (onError) {
105219                         onError(e.message);
105220                     }
105221                     text = "";
105222                 }
105223                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105224             },
105225             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105226             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105227             writeFile: writeFile,
105228             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105229             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105230             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105231             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105232             fileExists: function (f) { return host.fileExists(f); },
105233             readFile: function (f) { return host.readFile(f); },
105234             trace: ts.maybeBind(host, host.trace),
105235             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105236             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105237             realpath: ts.maybeBind(host, host.realpath),
105238             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105239             createHash: ts.maybeBind(host, host.createHash),
105240             readDirectory: ts.maybeBind(host, host.readDirectory),
105241         };
105242         function writeFile(fileName, text, writeByteOrderMark, onError) {
105243             try {
105244                 ts.performance.mark("beforeIOWrite");
105245                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105246                 // the host.writeFile will do its own directory creation and
105247                 // the ensureDirectoriesExist call will always be redundant.
105248                 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); });
105249                 ts.performance.mark("afterIOWrite");
105250                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105251             }
105252             catch (e) {
105253                 if (onError) {
105254                     onError(e.message);
105255                 }
105256             }
105257         }
105258     }
105259     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105260     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105261         var originalGetSourceFile = compilerHost.getSourceFile;
105262         var computeHash = host.createHash || ts.generateDjb2Hash;
105263         compilerHost.getSourceFile = function () {
105264             var args = [];
105265             for (var _i = 0; _i < arguments.length; _i++) {
105266                 args[_i] = arguments[_i];
105267             }
105268             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105269             if (result) {
105270                 result.version = computeHash.call(host, result.text);
105271             }
105272             return result;
105273         };
105274     }
105275     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105276     /**
105277      * Creates the watch compiler host that can be extended with config file or root file names and options host
105278      */
105279     function createProgramHost(system, createProgram) {
105280         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105281         return {
105282             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105283             getNewLine: function () { return system.newLine; },
105284             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105285             getDefaultLibLocation: getDefaultLibLocation,
105286             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105287             fileExists: function (path) { return system.fileExists(path); },
105288             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105289             directoryExists: function (path) { return system.directoryExists(path); },
105290             getDirectories: function (path) { return system.getDirectories(path); },
105291             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105292             realpath: ts.maybeBind(system, system.realpath),
105293             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105294             trace: function (s) { return system.write(s + system.newLine); },
105295             createDirectory: function (path) { return system.createDirectory(path); },
105296             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105297             createHash: ts.maybeBind(system, system.createHash),
105298             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105299         };
105300     }
105301     ts.createProgramHost = createProgramHost;
105302     /**
105303      * Creates the watch compiler host that can be extended with config file or root file names and options host
105304      */
105305     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105306         if (system === void 0) { system = ts.sys; }
105307         var writeFileName = function (s) { return system.write(s + system.newLine); };
105308         var result = createProgramHost(system, createProgram);
105309         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105310         result.afterProgramCreate = function (builderProgram) {
105311             var compilerOptions = builderProgram.getCompilerOptions();
105312             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105313             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105314         };
105315         return result;
105316     }
105317     /**
105318      * Report error and exit
105319      */
105320     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105321         reportDiagnostic(diagnostic);
105322         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105323     }
105324     /**
105325      * Creates the watch compiler host from system for config file in watch mode
105326      */
105327     function createWatchCompilerHostOfConfigFile(_a) {
105328         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;
105329         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105330         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105331         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105332         host.configFileName = configFileName;
105333         host.optionsToExtend = optionsToExtend;
105334         host.watchOptionsToExtend = watchOptionsToExtend;
105335         host.extraFileExtensions = extraFileExtensions;
105336         return host;
105337     }
105338     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105339     /**
105340      * Creates the watch compiler host from system for compiling root files and options in watch mode
105341      */
105342     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105343         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;
105344         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105345         host.rootFiles = rootFiles;
105346         host.options = options;
105347         host.watchOptions = watchOptions;
105348         host.projectReferences = projectReferences;
105349         return host;
105350     }
105351     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105352     function performIncrementalCompilation(input) {
105353         var system = input.system || ts.sys;
105354         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105355         var builderProgram = ts.createIncrementalProgram(input);
105356         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);
105357         if (input.afterProgramEmitAndDiagnostics)
105358             input.afterProgramEmitAndDiagnostics(builderProgram);
105359         return exitStatus;
105360     }
105361     ts.performIncrementalCompilation = performIncrementalCompilation;
105362 })(ts || (ts = {}));
105363 var ts;
105364 (function (ts) {
105365     function readBuilderProgram(compilerOptions, host) {
105366         if (compilerOptions.out || compilerOptions.outFile)
105367             return undefined;
105368         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105369         if (!buildInfoPath)
105370             return undefined;
105371         var content = host.readFile(buildInfoPath);
105372         if (!content)
105373             return undefined;
105374         var buildInfo = ts.getBuildInfo(content);
105375         if (buildInfo.version !== ts.version)
105376             return undefined;
105377         if (!buildInfo.program)
105378             return undefined;
105379         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105380     }
105381     ts.readBuilderProgram = readBuilderProgram;
105382     function createIncrementalCompilerHost(options, system) {
105383         if (system === void 0) { system = ts.sys; }
105384         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105385         host.createHash = ts.maybeBind(system, system.createHash);
105386         ts.setGetSourceFileAsHashVersioned(host, system);
105387         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105388         return host;
105389     }
105390     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105391     function createIncrementalProgram(_a) {
105392         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105393         host = host || createIncrementalCompilerHost(options);
105394         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105395         var oldProgram = readBuilderProgram(options, host);
105396         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105397     }
105398     ts.createIncrementalProgram = createIncrementalProgram;
105399     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105400         if (ts.isArray(rootFilesOrConfigFileName)) {
105401             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105402                 rootFiles: rootFilesOrConfigFileName,
105403                 options: options,
105404                 watchOptions: watchOptionsOrExtraFileExtensions,
105405                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105406                 system: system,
105407                 createProgram: createProgram,
105408                 reportDiagnostic: reportDiagnostic,
105409                 reportWatchStatus: reportWatchStatus,
105410             });
105411         }
105412         else {
105413             return ts.createWatchCompilerHostOfConfigFile({
105414                 configFileName: rootFilesOrConfigFileName,
105415                 optionsToExtend: options,
105416                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105417                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105418                 system: system,
105419                 createProgram: createProgram,
105420                 reportDiagnostic: reportDiagnostic,
105421                 reportWatchStatus: reportWatchStatus,
105422             });
105423         }
105424     }
105425     ts.createWatchCompilerHost = createWatchCompilerHost;
105426     function createWatchProgram(host) {
105427         var builderProgram;
105428         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105429         var missingFilesMap; // Map of file watchers for the missing files
105430         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105431         var timerToUpdateProgram; // timer callback to recompile the program
105432         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105433         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
105434         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105435         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105436         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105437         var currentDirectory = host.getCurrentDirectory();
105438         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105439         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105440         var configFileSpecs;
105441         var configFileParsingDiagnostics;
105442         var canConfigFileJsonReportNoInputFiles = false;
105443         var hasChangedConfigFileParsingErrors = false;
105444         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105445         var directoryStructureHost = cachedDirectoryStructureHost || host;
105446         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105447         // From tsc we want to get already parsed result and hence check for rootFileNames
105448         var newLine = updateNewLine();
105449         if (configFileName && host.configFileParsingResult) {
105450             setConfigFileParsingResult(host.configFileParsingResult);
105451             newLine = updateNewLine();
105452         }
105453         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105454         if (configFileName && !host.configFileParsingResult) {
105455             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105456             ts.Debug.assert(!rootFileNames);
105457             parseConfigFile();
105458             newLine = updateNewLine();
105459         }
105460         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105461         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105462         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105463         var configFileWatcher;
105464         if (configFileName) {
105465             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105466         }
105467         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105468         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105469         // Members for CompilerHost
105470         var getNewSourceFile = compilerHost.getSourceFile;
105471         compilerHost.getSourceFile = function (fileName) {
105472             var args = [];
105473             for (var _i = 1; _i < arguments.length; _i++) {
105474                 args[_i - 1] = arguments[_i];
105475             }
105476             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105477         };
105478         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105479         compilerHost.getNewLine = function () { return newLine; };
105480         compilerHost.fileExists = fileExists;
105481         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105482         // Members for ResolutionCacheHost
105483         compilerHost.toPath = toPath;
105484         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105485         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105486         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105487         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105488         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105489         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105490         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105491             hasChangedAutomaticTypeDirectiveNames = true;
105492             scheduleProgramUpdate();
105493         };
105494         compilerHost.fileIsOpen = ts.returnFalse;
105495         compilerHost.getCurrentProgram = getCurrentProgram;
105496         compilerHost.writeLog = writeLog;
105497         // Cache for the module resolution
105498         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105499             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105500             currentDirectory, 
105501         /*logChangesWhenResolvingModule*/ false);
105502         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105503         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105504             (function () {
105505                 var args = [];
105506                 for (var _i = 0; _i < arguments.length; _i++) {
105507                     args[_i] = arguments[_i];
105508                 }
105509                 return host.resolveModuleNames.apply(host, args);
105510             }) :
105511             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105512         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105513             (function () {
105514                 var args = [];
105515                 for (var _i = 0; _i < arguments.length; _i++) {
105516                     args[_i] = arguments[_i];
105517                 }
105518                 return host.resolveTypeReferenceDirectives.apply(host, args);
105519             }) :
105520             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105521         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105522         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105523         synchronizeProgram();
105524         // Update the wild card directory watch
105525         watchConfigFileWildCardDirectories();
105526         return configFileName ?
105527             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105528             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105529         function close() {
105530             resolutionCache.clear();
105531             ts.clearMap(sourceFilesCache, function (value) {
105532                 if (value && value.fileWatcher) {
105533                     value.fileWatcher.close();
105534                     value.fileWatcher = undefined;
105535                 }
105536             });
105537             if (configFileWatcher) {
105538                 configFileWatcher.close();
105539                 configFileWatcher = undefined;
105540             }
105541             if (watchedWildcardDirectories) {
105542                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105543                 watchedWildcardDirectories = undefined;
105544             }
105545             if (missingFilesMap) {
105546                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105547                 missingFilesMap = undefined;
105548             }
105549         }
105550         function getCurrentBuilderProgram() {
105551             return builderProgram;
105552         }
105553         function getCurrentProgram() {
105554             return builderProgram && builderProgram.getProgramOrUndefined();
105555         }
105556         function synchronizeProgram() {
105557             writeLog("Synchronizing program");
105558             var program = getCurrentBuilderProgram();
105559             if (hasChangedCompilerOptions) {
105560                 newLine = updateNewLine();
105561                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105562                     resolutionCache.clear();
105563                 }
105564             }
105565             // All resolutions are invalid if user provided resolutions
105566             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105567             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105568                 if (hasChangedConfigFileParsingErrors) {
105569                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105570                     hasChangedConfigFileParsingErrors = false;
105571                 }
105572             }
105573             else {
105574                 createNewProgram(hasInvalidatedResolution);
105575             }
105576             if (host.afterProgramCreate && program !== builderProgram) {
105577                 host.afterProgramCreate(builderProgram);
105578             }
105579             return builderProgram;
105580         }
105581         function createNewProgram(hasInvalidatedResolution) {
105582             // Compile the program
105583             writeLog("CreatingProgramWith::");
105584             writeLog("  roots: " + JSON.stringify(rootFileNames));
105585             writeLog("  options: " + JSON.stringify(compilerOptions));
105586             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105587             hasChangedCompilerOptions = false;
105588             hasChangedConfigFileParsingErrors = false;
105589             resolutionCache.startCachingPerDirectoryResolution();
105590             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105591             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105592             hasChangedAutomaticTypeDirectiveNames = false;
105593             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105594             resolutionCache.finishCachingPerDirectoryResolution();
105595             // Update watches
105596             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105597             if (needsUpdateInTypeRootWatch) {
105598                 resolutionCache.updateTypeRootsWatch();
105599             }
105600             if (missingFilePathsRequestedForRelease) {
105601                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105602                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105603                 // if there is already watcher for it (for missing files)
105604                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105605                 // so that at later time we have correct result of their presence
105606                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105607                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105608                     if (!missingFilesMap.has(missingFilePath)) {
105609                         sourceFilesCache.delete(missingFilePath);
105610                     }
105611                 }
105612                 missingFilePathsRequestedForRelease = undefined;
105613             }
105614         }
105615         function updateRootFileNames(files) {
105616             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105617             rootFileNames = files;
105618             scheduleProgramUpdate();
105619         }
105620         function updateNewLine() {
105621             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105622         }
105623         function toPath(fileName) {
105624             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105625         }
105626         function isFileMissingOnHost(hostSourceFile) {
105627             return typeof hostSourceFile === "boolean";
105628         }
105629         function isFilePresenceUnknownOnHost(hostSourceFile) {
105630             return typeof hostSourceFile.version === "boolean";
105631         }
105632         function fileExists(fileName) {
105633             var path = toPath(fileName);
105634             // If file is missing on host from cache, we can definitely say file doesnt exist
105635             // otherwise we need to ensure from the disk
105636             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105637                 return false;
105638             }
105639             return directoryStructureHost.fileExists(fileName);
105640         }
105641         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105642             var hostSourceFile = sourceFilesCache.get(path);
105643             // No source file on the host
105644             if (isFileMissingOnHost(hostSourceFile)) {
105645                 return undefined;
105646             }
105647             // Create new source file if requested or the versions dont match
105648             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105649                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105650                 if (hostSourceFile) {
105651                     if (sourceFile) {
105652                         // Set the source file and create file watcher now that file was present on the disk
105653                         hostSourceFile.sourceFile = sourceFile;
105654                         hostSourceFile.version = sourceFile.version;
105655                         if (!hostSourceFile.fileWatcher) {
105656                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105657                         }
105658                     }
105659                     else {
105660                         // There is no source file on host any more, close the watch, missing file paths will track it
105661                         if (hostSourceFile.fileWatcher) {
105662                             hostSourceFile.fileWatcher.close();
105663                         }
105664                         sourceFilesCache.set(path, false);
105665                     }
105666                 }
105667                 else {
105668                     if (sourceFile) {
105669                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105670                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105671                     }
105672                     else {
105673                         sourceFilesCache.set(path, false);
105674                     }
105675                 }
105676                 return sourceFile;
105677             }
105678             return hostSourceFile.sourceFile;
105679         }
105680         function nextSourceFileVersion(path) {
105681             var hostSourceFile = sourceFilesCache.get(path);
105682             if (hostSourceFile !== undefined) {
105683                 if (isFileMissingOnHost(hostSourceFile)) {
105684                     // The next version, lets set it as presence unknown file
105685                     sourceFilesCache.set(path, { version: false });
105686                 }
105687                 else {
105688                     hostSourceFile.version = false;
105689                 }
105690             }
105691         }
105692         function getSourceVersion(path) {
105693             var hostSourceFile = sourceFilesCache.get(path);
105694             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105695         }
105696         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105697             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105698             // If this is the source file thats in the cache and new program doesnt need it,
105699             // remove the cached entry.
105700             // Note we arent deleting entry if file became missing in new program or
105701             // there was version update and new source file was created.
105702             if (hostSourceFileInfo !== undefined) {
105703                 // record the missing file paths so they can be removed later if watchers arent tracking them
105704                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105705                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105706                 }
105707                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105708                     if (hostSourceFileInfo.fileWatcher) {
105709                         hostSourceFileInfo.fileWatcher.close();
105710                     }
105711                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105712                     if (!hasSourceFileByPath) {
105713                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105714                     }
105715                 }
105716             }
105717         }
105718         function reportWatchDiagnostic(message) {
105719             if (host.onWatchStatusChange) {
105720                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105721             }
105722         }
105723         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105724         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105725         // off a new compilation.
105726         function scheduleProgramUpdate() {
105727             if (!host.setTimeout || !host.clearTimeout) {
105728                 return;
105729             }
105730             if (timerToUpdateProgram) {
105731                 host.clearTimeout(timerToUpdateProgram);
105732             }
105733             writeLog("Scheduling update");
105734             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105735         }
105736         function scheduleProgramReload() {
105737             ts.Debug.assert(!!configFileName);
105738             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105739             scheduleProgramUpdate();
105740         }
105741         function updateProgramWithWatchStatus() {
105742             timerToUpdateProgram = undefined;
105743             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105744             updateProgram();
105745         }
105746         function updateProgram() {
105747             switch (reloadLevel) {
105748                 case ts.ConfigFileProgramReloadLevel.Partial:
105749                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105750                     reloadFileNamesFromConfigFile();
105751                     break;
105752                 case ts.ConfigFileProgramReloadLevel.Full:
105753                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105754                     reloadConfigFile();
105755                     break;
105756                 default:
105757                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105758                     synchronizeProgram();
105759                     break;
105760             }
105761             ts.perfLogger.logStopUpdateProgram("Done");
105762             return getCurrentBuilderProgram();
105763         }
105764         function reloadFileNamesFromConfigFile() {
105765             writeLog("Reloading new file names and options");
105766             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105767             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105768                 hasChangedConfigFileParsingErrors = true;
105769             }
105770             rootFileNames = result.fileNames;
105771             // Update the program
105772             synchronizeProgram();
105773         }
105774         function reloadConfigFile() {
105775             writeLog("Reloading config file: " + configFileName);
105776             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105777             if (cachedDirectoryStructureHost) {
105778                 cachedDirectoryStructureHost.clearCache();
105779             }
105780             parseConfigFile();
105781             hasChangedCompilerOptions = true;
105782             synchronizeProgram();
105783             // Update the wild card directory watch
105784             watchConfigFileWildCardDirectories();
105785         }
105786         function parseConfigFile() {
105787             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105788         }
105789         function setConfigFileParsingResult(configFileParseResult) {
105790             rootFileNames = configFileParseResult.fileNames;
105791             compilerOptions = configFileParseResult.options;
105792             watchOptions = configFileParseResult.watchOptions;
105793             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105794             projectReferences = configFileParseResult.projectReferences;
105795             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105796             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105797             hasChangedConfigFileParsingErrors = true;
105798         }
105799         function onSourceFileChange(fileName, eventKind, path) {
105800             updateCachedSystemWithFile(fileName, path, eventKind);
105801             // Update the source file cache
105802             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105803                 resolutionCache.invalidateResolutionOfFile(path);
105804             }
105805             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105806             nextSourceFileVersion(path);
105807             // Update the program
105808             scheduleProgramUpdate();
105809         }
105810         function updateCachedSystemWithFile(fileName, path, eventKind) {
105811             if (cachedDirectoryStructureHost) {
105812                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
105813             }
105814         }
105815         function watchMissingFilePath(missingFilePath) {
105816             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
105817         }
105818         function onMissingFileChange(fileName, eventKind, missingFilePath) {
105819             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
105820             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
105821                 missingFilesMap.get(missingFilePath).close();
105822                 missingFilesMap.delete(missingFilePath);
105823                 // Delete the entry in the source files cache so that new source file is created
105824                 nextSourceFileVersion(missingFilePath);
105825                 // When a missing file is created, we should update the graph.
105826                 scheduleProgramUpdate();
105827             }
105828         }
105829         function watchConfigFileWildCardDirectories() {
105830             if (configFileSpecs) {
105831                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
105832             }
105833             else if (watchedWildcardDirectories) {
105834                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105835             }
105836         }
105837         function watchWildcardDirectory(directory, flags) {
105838             return watchDirectory(host, directory, function (fileOrDirectory) {
105839                 ts.Debug.assert(!!configFileName);
105840                 var fileOrDirectoryPath = toPath(fileOrDirectory);
105841                 // Since the file existence changed, update the sourceFiles cache
105842                 if (cachedDirectoryStructureHost) {
105843                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
105844                 }
105845                 nextSourceFileVersion(fileOrDirectoryPath);
105846                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105847                 if (!fileOrDirectoryPath)
105848                     return;
105849                 // If the the added or created file or directory is not supported file name, ignore the file
105850                 // But when watched directory is added/removed, we need to reload the file list
105851                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
105852                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105853                     return;
105854                 }
105855                 // Reload is pending, do the reload
105856                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
105857                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
105858                     // Schedule Update the program
105859                     scheduleProgramUpdate();
105860                 }
105861             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
105862         }
105863     }
105864     ts.createWatchProgram = createWatchProgram;
105865 })(ts || (ts = {}));
105866 /*@internal*/
105867 var ts;
105868 (function (ts) {
105869     var UpToDateStatusType;
105870     (function (UpToDateStatusType) {
105871         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
105872         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
105873         /**
105874          * The project appears out of date because its upstream inputs are newer than its outputs,
105875          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105876          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
105877          */
105878         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
105879         /**
105880          * The project appears out of date because its upstream inputs are newer than its outputs,
105881          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105882          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
105883          */
105884         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
105885         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
105886         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
105887         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
105888         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
105889         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
105890         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
105891         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
105892         /**
105893          * Projects with no outputs (i.e. "solution" files)
105894          */
105895         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
105896     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
105897     function resolveConfigFileProjectName(project) {
105898         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
105899             return project;
105900         }
105901         return ts.combinePaths(project, "tsconfig.json");
105902     }
105903     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
105904 })(ts || (ts = {}));
105905 var ts;
105906 (function (ts) {
105907     var minimumDate = new Date(-8640000000000000);
105908     var maximumDate = new Date(8640000000000000);
105909     var BuildResultFlags;
105910     (function (BuildResultFlags) {
105911         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
105912         /**
105913          * No errors of any kind occurred during build
105914          */
105915         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
105916         /**
105917          * None of the .d.ts files emitted by this build were
105918          * different from the existing files on disk
105919          */
105920         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
105921         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
105922         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
105923         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
105924         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
105925         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
105926         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
105927     })(BuildResultFlags || (BuildResultFlags = {}));
105928     function createConfigFileMap() {
105929         return ts.createMap();
105930     }
105931     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
105932         var existingValue = configFileMap.get(resolved);
105933         var newValue;
105934         if (!existingValue) {
105935             newValue = createT();
105936             configFileMap.set(resolved, newValue);
105937         }
105938         return existingValue || newValue;
105939     }
105940     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
105941         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
105942     }
105943     function newer(date1, date2) {
105944         return date2 > date1 ? date2 : date1;
105945     }
105946     function isDeclarationFile(fileName) {
105947         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
105948     }
105949     /*@internal*/
105950     function isCircularBuildOrder(buildOrder) {
105951         return !!buildOrder && !!buildOrder.buildOrder;
105952     }
105953     ts.isCircularBuildOrder = isCircularBuildOrder;
105954     /*@internal*/
105955     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
105956         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
105957     }
105958     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
105959     /**
105960      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105961      */
105962     function createBuilderStatusReporter(system, pretty) {
105963         return function (diagnostic) {
105964             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
105965             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
105966             system.write(output);
105967         };
105968     }
105969     ts.createBuilderStatusReporter = createBuilderStatusReporter;
105970     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
105971         var host = ts.createProgramHost(system, createProgram);
105972         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
105973         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
105974         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
105975         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
105976         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
105977         host.now = ts.maybeBind(system, system.now); // For testing
105978         return host;
105979     }
105980     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
105981         if (system === void 0) { system = ts.sys; }
105982         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
105983         host.reportErrorSummary = reportErrorSummary;
105984         return host;
105985     }
105986     ts.createSolutionBuilderHost = createSolutionBuilderHost;
105987     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
105988         if (system === void 0) { system = ts.sys; }
105989         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
105990         var watchHost = ts.createWatchHost(system, reportWatchStatus);
105991         ts.copyProperties(host, watchHost);
105992         return host;
105993     }
105994     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
105995     function getCompilerOptionsOfBuildOptions(buildOptions) {
105996         var result = {};
105997         ts.commonOptionsWithBuild.forEach(function (option) {
105998             if (ts.hasProperty(buildOptions, option.name))
105999                 result[option.name] = buildOptions[option.name];
106000         });
106001         return result;
106002     }
106003     function createSolutionBuilder(host, rootNames, defaultOptions) {
106004         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106005     }
106006     ts.createSolutionBuilder = createSolutionBuilder;
106007     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106008         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106009     }
106010     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106011     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106012         var host = hostOrHostWithWatch;
106013         var hostWithWatch = hostOrHostWithWatch;
106014         var currentDirectory = host.getCurrentDirectory();
106015         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106016         // State of the solution
106017         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106018         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106019         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106020         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106021         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106022         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106023         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106024         if (!compilerHost.resolveModuleNames) {
106025             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106026             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106027                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106028             };
106029         }
106030         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106031         var state = {
106032             host: host,
106033             hostWithWatch: hostWithWatch,
106034             currentDirectory: currentDirectory,
106035             getCanonicalFileName: getCanonicalFileName,
106036             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106037             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106038             // State of solution
106039             options: options,
106040             baseCompilerOptions: baseCompilerOptions,
106041             rootNames: rootNames,
106042             baseWatchOptions: baseWatchOptions,
106043             resolvedConfigFilePaths: ts.createMap(),
106044             configFileCache: createConfigFileMap(),
106045             projectStatus: createConfigFileMap(),
106046             buildInfoChecked: createConfigFileMap(),
106047             extendedConfigCache: ts.createMap(),
106048             builderPrograms: createConfigFileMap(),
106049             diagnostics: createConfigFileMap(),
106050             projectPendingBuild: createConfigFileMap(),
106051             projectErrorsReported: createConfigFileMap(),
106052             compilerHost: compilerHost,
106053             moduleResolutionCache: moduleResolutionCache,
106054             // Mutable state
106055             buildOrder: undefined,
106056             readFileWithCache: function (f) { return host.readFile(f); },
106057             projectCompilerOptions: baseCompilerOptions,
106058             cache: undefined,
106059             allProjectBuildPending: true,
106060             needsSummary: true,
106061             watchAllProjectsPending: watch,
106062             currentInvalidatedProject: undefined,
106063             // Watch state
106064             watch: watch,
106065             allWatchedWildcardDirectories: createConfigFileMap(),
106066             allWatchedInputFiles: createConfigFileMap(),
106067             allWatchedConfigFiles: createConfigFileMap(),
106068             timerToBuildInvalidatedProject: undefined,
106069             reportFileChangeDetected: false,
106070             watchFile: watchFile,
106071             watchFilePath: watchFilePath,
106072             watchDirectory: watchDirectory,
106073             writeLog: writeLog,
106074         };
106075         return state;
106076     }
106077     function toPath(state, fileName) {
106078         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106079     }
106080     function toResolvedConfigFilePath(state, fileName) {
106081         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106082         var path = resolvedConfigFilePaths.get(fileName);
106083         if (path !== undefined)
106084             return path;
106085         var resolvedPath = toPath(state, fileName);
106086         resolvedConfigFilePaths.set(fileName, resolvedPath);
106087         return resolvedPath;
106088     }
106089     function isParsedCommandLine(entry) {
106090         return !!entry.options;
106091     }
106092     function parseConfigFile(state, configFileName, configFilePath) {
106093         var configFileCache = state.configFileCache;
106094         var value = configFileCache.get(configFilePath);
106095         if (value) {
106096             return isParsedCommandLine(value) ? value : undefined;
106097         }
106098         var diagnostic;
106099         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106100         var parsed;
106101         if (host.getParsedCommandLine) {
106102             parsed = host.getParsedCommandLine(configFileName);
106103             if (!parsed)
106104                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106105         }
106106         else {
106107             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106108             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106109             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106110         }
106111         configFileCache.set(configFilePath, parsed || diagnostic);
106112         return parsed;
106113     }
106114     function resolveProjectName(state, name) {
106115         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106116     }
106117     function createBuildOrder(state, roots) {
106118         var temporaryMarks = ts.createMap();
106119         var permanentMarks = ts.createMap();
106120         var circularityReportStack = [];
106121         var buildOrder;
106122         var circularDiagnostics;
106123         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106124             var root = roots_1[_i];
106125             visit(root);
106126         }
106127         return circularDiagnostics ?
106128             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106129             buildOrder || ts.emptyArray;
106130         function visit(configFileName, inCircularContext) {
106131             var projPath = toResolvedConfigFilePath(state, configFileName);
106132             // Already visited
106133             if (permanentMarks.has(projPath))
106134                 return;
106135             // Circular
106136             if (temporaryMarks.has(projPath)) {
106137                 if (!inCircularContext) {
106138                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106139                 }
106140                 return;
106141             }
106142             temporaryMarks.set(projPath, true);
106143             circularityReportStack.push(configFileName);
106144             var parsed = parseConfigFile(state, configFileName, projPath);
106145             if (parsed && parsed.projectReferences) {
106146                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106147                     var ref = _a[_i];
106148                     var resolvedRefPath = resolveProjectName(state, ref.path);
106149                     visit(resolvedRefPath, inCircularContext || ref.circular);
106150                 }
106151             }
106152             circularityReportStack.pop();
106153             permanentMarks.set(projPath, true);
106154             (buildOrder || (buildOrder = [])).push(configFileName);
106155         }
106156     }
106157     function getBuildOrder(state) {
106158         return state.buildOrder || createStateBuildOrder(state);
106159     }
106160     function createStateBuildOrder(state) {
106161         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106162         // Clear all to ResolvedConfigFilePaths cache to start fresh
106163         state.resolvedConfigFilePaths.clear();
106164         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106165         var noopOnDelete = { onDeleteValue: ts.noop };
106166         // Config file cache
106167         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106168         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106169         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106170         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106171         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106172         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106173         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106174         // Remove watches for the program no longer in the solution
106175         if (state.watch) {
106176             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106177             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106178             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106179         }
106180         return state.buildOrder = buildOrder;
106181     }
106182     function getBuildOrderFor(state, project, onlyReferences) {
106183         var resolvedProject = project && resolveProjectName(state, project);
106184         var buildOrderFromState = getBuildOrder(state);
106185         if (isCircularBuildOrder(buildOrderFromState))
106186             return buildOrderFromState;
106187         if (resolvedProject) {
106188             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106189             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106190             if (projectIndex === -1)
106191                 return undefined;
106192         }
106193         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106194         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106195         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106196         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106197         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106198     }
106199     function enableCache(state) {
106200         if (state.cache) {
106201             disableCache(state);
106202         }
106203         var compilerHost = state.compilerHost, host = state.host;
106204         var originalReadFileWithCache = state.readFileWithCache;
106205         var originalGetSourceFile = compilerHost.getSourceFile;
106206         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106207             var args = [];
106208             for (var _i = 0; _i < arguments.length; _i++) {
106209                 args[_i] = arguments[_i];
106210             }
106211             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106212         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106213         state.readFileWithCache = readFileWithCache;
106214         compilerHost.getSourceFile = getSourceFileWithCache;
106215         state.cache = {
106216             originalReadFile: originalReadFile,
106217             originalFileExists: originalFileExists,
106218             originalDirectoryExists: originalDirectoryExists,
106219             originalCreateDirectory: originalCreateDirectory,
106220             originalWriteFile: originalWriteFile,
106221             originalReadFileWithCache: originalReadFileWithCache,
106222             originalGetSourceFile: originalGetSourceFile,
106223         };
106224     }
106225     function disableCache(state) {
106226         if (!state.cache)
106227             return;
106228         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106229         host.readFile = cache.originalReadFile;
106230         host.fileExists = cache.originalFileExists;
106231         host.directoryExists = cache.originalDirectoryExists;
106232         host.createDirectory = cache.originalCreateDirectory;
106233         host.writeFile = cache.originalWriteFile;
106234         compilerHost.getSourceFile = cache.originalGetSourceFile;
106235         state.readFileWithCache = cache.originalReadFileWithCache;
106236         extendedConfigCache.clear();
106237         if (moduleResolutionCache) {
106238             moduleResolutionCache.directoryToModuleNameMap.clear();
106239             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106240         }
106241         state.cache = undefined;
106242     }
106243     function clearProjectStatus(state, resolved) {
106244         state.projectStatus.delete(resolved);
106245         state.diagnostics.delete(resolved);
106246     }
106247     function addProjToQueue(_a, proj, reloadLevel) {
106248         var projectPendingBuild = _a.projectPendingBuild;
106249         var value = projectPendingBuild.get(proj);
106250         if (value === undefined) {
106251             projectPendingBuild.set(proj, reloadLevel);
106252         }
106253         else if (value < reloadLevel) {
106254             projectPendingBuild.set(proj, reloadLevel);
106255         }
106256     }
106257     function setupInitialBuild(state, cancellationToken) {
106258         // Set initial build if not already built
106259         if (!state.allProjectBuildPending)
106260             return;
106261         state.allProjectBuildPending = false;
106262         if (state.options.watch) {
106263             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106264         }
106265         enableCache(state);
106266         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106267         buildOrder.forEach(function (configFileName) {
106268             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106269         });
106270         if (cancellationToken) {
106271             cancellationToken.throwIfCancellationRequested();
106272         }
106273     }
106274     var InvalidatedProjectKind;
106275     (function (InvalidatedProjectKind) {
106276         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106277         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106278         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106279     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106280     function doneInvalidatedProject(state, projectPath) {
106281         state.projectPendingBuild.delete(projectPath);
106282         state.currentInvalidatedProject = undefined;
106283         return state.diagnostics.has(projectPath) ?
106284             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106285             ts.ExitStatus.Success;
106286     }
106287     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106288         var updateOutputFileStampsPending = true;
106289         return {
106290             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106291             project: project,
106292             projectPath: projectPath,
106293             buildOrder: buildOrder,
106294             getCompilerOptions: function () { return config.options; },
106295             getCurrentDirectory: function () { return state.currentDirectory; },
106296             updateOutputFileStatmps: function () {
106297                 updateOutputTimestamps(state, config, projectPath);
106298                 updateOutputFileStampsPending = false;
106299             },
106300             done: function () {
106301                 if (updateOutputFileStampsPending) {
106302                     updateOutputTimestamps(state, config, projectPath);
106303                 }
106304                 return doneInvalidatedProject(state, projectPath);
106305             }
106306         };
106307     }
106308     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106309         var Step;
106310         (function (Step) {
106311             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106312             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106313             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106314             Step[Step["Emit"] = 3] = "Emit";
106315             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106316             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106317             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106318             Step[Step["Done"] = 7] = "Done";
106319         })(Step || (Step = {}));
106320         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106321         var program;
106322         var buildResult;
106323         var invalidatedProjectOfBundle;
106324         return kind === InvalidatedProjectKind.Build ?
106325             {
106326                 kind: kind,
106327                 project: project,
106328                 projectPath: projectPath,
106329                 buildOrder: buildOrder,
106330                 getCompilerOptions: function () { return config.options; },
106331                 getCurrentDirectory: function () { return state.currentDirectory; },
106332                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106333                 getProgram: function () {
106334                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106335                 },
106336                 getSourceFile: function (fileName) {
106337                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106338                 },
106339                 getSourceFiles: function () {
106340                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106341                 },
106342                 getOptionsDiagnostics: function (cancellationToken) {
106343                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106344                 },
106345                 getGlobalDiagnostics: function (cancellationToken) {
106346                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106347                 },
106348                 getConfigFileParsingDiagnostics: function () {
106349                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106350                 },
106351                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106352                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106353                 },
106354                 getAllDependencies: function (sourceFile) {
106355                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106356                 },
106357                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106358                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106359                 },
106360                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106361                     return withProgramOrUndefined(function (program) {
106362                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106363                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106364                     });
106365                 },
106366                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106367                     if (targetSourceFile || emitOnlyDtsFiles) {
106368                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106369                     }
106370                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106371                     if (step !== Step.Emit)
106372                         return undefined;
106373                     return emit(writeFile, cancellationToken, customTransformers);
106374                 },
106375                 done: done
106376             } :
106377             {
106378                 kind: kind,
106379                 project: project,
106380                 projectPath: projectPath,
106381                 buildOrder: buildOrder,
106382                 getCompilerOptions: function () { return config.options; },
106383                 getCurrentDirectory: function () { return state.currentDirectory; },
106384                 emit: function (writeFile, customTransformers) {
106385                     if (step !== Step.EmitBundle)
106386                         return invalidatedProjectOfBundle;
106387                     return emitBundle(writeFile, customTransformers);
106388                 },
106389                 done: done,
106390             };
106391         function done(cancellationToken, writeFile, customTransformers) {
106392             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106393             return doneInvalidatedProject(state, projectPath);
106394         }
106395         function withProgramOrUndefined(action) {
106396             executeSteps(Step.CreateProgram);
106397             return program && action(program);
106398         }
106399         function withProgramOrEmptyArray(action) {
106400             return withProgramOrUndefined(action) || ts.emptyArray;
106401         }
106402         function createProgram() {
106403             ts.Debug.assert(program === undefined);
106404             if (state.options.dry) {
106405                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106406                 buildResult = BuildResultFlags.Success;
106407                 step = Step.QueueReferencingProjects;
106408                 return;
106409             }
106410             if (state.options.verbose)
106411                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106412             if (config.fileNames.length === 0) {
106413                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106414                 // Nothing to build - must be a solution file, basically
106415                 buildResult = BuildResultFlags.None;
106416                 step = Step.QueueReferencingProjects;
106417                 return;
106418             }
106419             var host = state.host, compilerHost = state.compilerHost;
106420             state.projectCompilerOptions = config.options;
106421             // Update module resolution cache if needed
106422             updateModuleResolutionCache(state, project, config);
106423             // Create program
106424             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106425             step++;
106426         }
106427         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106428             if (diagnostics.length) {
106429                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106430                 step = Step.QueueReferencingProjects;
106431             }
106432             else {
106433                 step++;
106434             }
106435         }
106436         function getSyntaxDiagnostics(cancellationToken) {
106437             ts.Debug.assertIsDefined(program);
106438             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106439         }
106440         function getSemanticDiagnostics(cancellationToken) {
106441             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106442         }
106443         function emit(writeFileCallback, cancellationToken, customTransformers) {
106444             ts.Debug.assertIsDefined(program);
106445             ts.Debug.assert(step === Step.Emit);
106446             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106447             program.backupState();
106448             var declDiagnostics;
106449             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106450             var outputFiles = [];
106451             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106452             /*writeFileName*/ undefined, 
106453             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106454             /*emitOnlyDts*/ false, customTransformers).emitResult;
106455             // Don't emit .d.ts if there are decl file errors
106456             if (declDiagnostics) {
106457                 program.restoreState();
106458                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106459                 step = Step.QueueReferencingProjects;
106460                 return {
106461                     emitSkipped: true,
106462                     diagnostics: emitResult.diagnostics
106463                 };
106464             }
106465             // Actual Emit
106466             var host = state.host, compilerHost = state.compilerHost;
106467             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106468             var newestDeclarationFileContentChangedTime = minimumDate;
106469             var anyDtsChanged = false;
106470             var emitterDiagnostics = ts.createDiagnosticCollection();
106471             var emittedOutputs = ts.createMap();
106472             outputFiles.forEach(function (_a) {
106473                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106474                 var priorChangeTime;
106475                 if (!anyDtsChanged && isDeclarationFile(name)) {
106476                     // Check for unchanged .d.ts files
106477                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106478                         priorChangeTime = host.getModifiedTime(name);
106479                     }
106480                     else {
106481                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106482                         anyDtsChanged = true;
106483                     }
106484                 }
106485                 emittedOutputs.set(toPath(state, name), name);
106486                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106487                 if (priorChangeTime !== undefined) {
106488                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106489                 }
106490             });
106491             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106492             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106493             return emitResult;
106494         }
106495         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106496             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106497             if (emitDiagnostics.length) {
106498                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106499                 step = Step.QueueReferencingProjects;
106500                 return emitDiagnostics;
106501             }
106502             if (state.writeFileName) {
106503                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106504                 if (program)
106505                     ts.listFiles(program, state.writeFileName);
106506             }
106507             // Update time stamps for rest of the outputs
106508             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106509             state.diagnostics.delete(projectPath);
106510             state.projectStatus.set(projectPath, {
106511                 type: ts.UpToDateStatusType.UpToDate,
106512                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106513                     maximumDate :
106514                     newestDeclarationFileContentChangedTime,
106515                 oldestOutputFileName: oldestOutputFileName
106516             });
106517             afterProgramDone(state, projectPath, program, config);
106518             state.projectCompilerOptions = state.baseCompilerOptions;
106519             step = Step.QueueReferencingProjects;
106520             buildResult = resultFlags;
106521             return emitDiagnostics;
106522         }
106523         function emitBundle(writeFileCallback, customTransformers) {
106524             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106525             if (state.options.dry) {
106526                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106527                 buildResult = BuildResultFlags.Success;
106528                 step = Step.QueueReferencingProjects;
106529                 return undefined;
106530             }
106531             if (state.options.verbose)
106532                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106533             // Update js, and source map
106534             var compilerHost = state.compilerHost;
106535             state.projectCompilerOptions = config.options;
106536             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106537                 var refName = resolveProjectName(state, ref.path);
106538                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106539             }, customTransformers);
106540             if (ts.isString(outputFiles)) {
106541                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106542                 step = Step.BuildInvalidatedProjectOfBundle;
106543                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106544             }
106545             // Actual Emit
106546             ts.Debug.assert(!!outputFiles.length);
106547             var emitterDiagnostics = ts.createDiagnosticCollection();
106548             var emittedOutputs = ts.createMap();
106549             outputFiles.forEach(function (_a) {
106550                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106551                 emittedOutputs.set(toPath(state, name), name);
106552                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106553             });
106554             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106555             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106556             return { emitSkipped: false, diagnostics: emitDiagnostics };
106557         }
106558         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106559             while (step <= till && step < Step.Done) {
106560                 var currentStep = step;
106561                 switch (step) {
106562                     case Step.CreateProgram:
106563                         createProgram();
106564                         break;
106565                     case Step.SyntaxDiagnostics:
106566                         getSyntaxDiagnostics(cancellationToken);
106567                         break;
106568                     case Step.SemanticDiagnostics:
106569                         getSemanticDiagnostics(cancellationToken);
106570                         break;
106571                     case Step.Emit:
106572                         emit(writeFile, cancellationToken, customTransformers);
106573                         break;
106574                     case Step.EmitBundle:
106575                         emitBundle(writeFile, customTransformers);
106576                         break;
106577                     case Step.BuildInvalidatedProjectOfBundle:
106578                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106579                         step = Step.Done;
106580                         break;
106581                     case Step.QueueReferencingProjects:
106582                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106583                         step++;
106584                         break;
106585                     // Should never be done
106586                     case Step.Done:
106587                     default:
106588                         ts.assertType(step);
106589                 }
106590                 ts.Debug.assert(step > currentStep);
106591             }
106592         }
106593     }
106594     function needsBuild(_a, status, config) {
106595         var options = _a.options;
106596         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106597             return true;
106598         return config.fileNames.length === 0 ||
106599             !!ts.getConfigFileParsingDiagnostics(config).length ||
106600             !ts.isIncrementalCompilation(config.options);
106601     }
106602     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106603         if (!state.projectPendingBuild.size)
106604             return undefined;
106605         if (isCircularBuildOrder(buildOrder))
106606             return undefined;
106607         if (state.currentInvalidatedProject) {
106608             // Only if same buildOrder the currentInvalidated project can be sent again
106609             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106610                 state.currentInvalidatedProject :
106611                 undefined;
106612         }
106613         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106614         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106615             var project = buildOrder[projectIndex];
106616             var projectPath = toResolvedConfigFilePath(state, project);
106617             var reloadLevel = state.projectPendingBuild.get(projectPath);
106618             if (reloadLevel === undefined)
106619                 continue;
106620             if (reportQueue) {
106621                 reportQueue = false;
106622                 reportBuildQueue(state, buildOrder);
106623             }
106624             var config = parseConfigFile(state, project, projectPath);
106625             if (!config) {
106626                 reportParseConfigFileDiagnostic(state, projectPath);
106627                 projectPendingBuild.delete(projectPath);
106628                 continue;
106629             }
106630             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106631                 watchConfigFile(state, project, projectPath, config);
106632                 watchWildCardDirectories(state, project, projectPath, config);
106633                 watchInputFiles(state, project, projectPath, config);
106634             }
106635             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106636                 // Update file names
106637                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106638                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106639                 config.fileNames = result.fileNames;
106640                 watchInputFiles(state, project, projectPath, config);
106641             }
106642             var status = getUpToDateStatus(state, config, projectPath);
106643             verboseReportProjectStatus(state, project, status);
106644             if (!options.force) {
106645                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106646                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106647                     projectPendingBuild.delete(projectPath);
106648                     // Up to date, skip
106649                     if (options.dry) {
106650                         // In a dry build, inform the user of this fact
106651                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106652                     }
106653                     continue;
106654                 }
106655                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106656                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106657                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106658                 }
106659             }
106660             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106661                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106662                 projectPendingBuild.delete(projectPath);
106663                 if (options.verbose) {
106664                     reportStatus(state, status.upstreamProjectBlocked ?
106665                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106666                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106667                 }
106668                 continue;
106669             }
106670             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106671                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106672                 projectPendingBuild.delete(projectPath);
106673                 // Do nothing
106674                 continue;
106675             }
106676             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106677                 InvalidatedProjectKind.Build :
106678                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106679         }
106680         return undefined;
106681     }
106682     function listEmittedFile(_a, proj, file) {
106683         var writeFileName = _a.writeFileName;
106684         if (writeFileName && proj.options.listEmittedFiles) {
106685             writeFileName("TSFILE: " + file);
106686         }
106687     }
106688     function getOldProgram(_a, proj, parsed) {
106689         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106690         if (options.force)
106691             return undefined;
106692         var value = builderPrograms.get(proj);
106693         if (value)
106694             return value;
106695         return ts.readBuilderProgram(parsed.options, compilerHost);
106696     }
106697     function afterProgramDone(_a, proj, program, config) {
106698         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106699         if (program) {
106700             if (host.afterProgramEmitAndDiagnostics) {
106701                 host.afterProgramEmitAndDiagnostics(program);
106702             }
106703             if (watch) {
106704                 program.releaseProgram();
106705                 builderPrograms.set(proj, program);
106706             }
106707         }
106708         else if (host.afterEmitBundle) {
106709             host.afterEmitBundle(config);
106710         }
106711     }
106712     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106713         reportAndStoreErrors(state, resolvedPath, diagnostics);
106714         // List files if any other build error using program (emit errors already report files)
106715         if (program && state.writeFileName)
106716             ts.listFiles(program, state.writeFileName);
106717         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106718         afterProgramDone(state, resolvedPath, program, config);
106719         state.projectCompilerOptions = state.baseCompilerOptions;
106720         return errorFlags;
106721     }
106722     function updateModuleResolutionCache(state, proj, config) {
106723         if (!state.moduleResolutionCache)
106724             return;
106725         // Update module resolution cache if needed
106726         var moduleResolutionCache = state.moduleResolutionCache;
106727         var projPath = toPath(state, proj);
106728         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106729             // The own map will be for projectCompilerOptions
106730             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106731             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106732             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106733         }
106734         else {
106735             // Set correct own map
106736             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106737             var ref = {
106738                 sourceFile: config.options.configFile,
106739                 commandLine: config
106740             };
106741             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106742             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106743         }
106744         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106745         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106746     }
106747     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106748         // Check tsconfig time
106749         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106750         if (oldestOutputFileTime < tsconfigTime) {
106751             return {
106752                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106753                 outOfDateOutputFileName: oldestOutputFileName,
106754                 newerInputFileName: configFile
106755             };
106756         }
106757     }
106758     function getUpToDateStatusWorker(state, project, resolvedPath) {
106759         var newestInputFileName = undefined;
106760         var newestInputFileTime = minimumDate;
106761         var host = state.host;
106762         // Get timestamps of input files
106763         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106764             var inputFile = _a[_i];
106765             if (!host.fileExists(inputFile)) {
106766                 return {
106767                     type: ts.UpToDateStatusType.Unbuildable,
106768                     reason: inputFile + " does not exist"
106769                 };
106770             }
106771             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106772             if (inputTime > newestInputFileTime) {
106773                 newestInputFileName = inputFile;
106774                 newestInputFileTime = inputTime;
106775             }
106776         }
106777         // Container if no files are specified in the project
106778         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106779             return {
106780                 type: ts.UpToDateStatusType.ContainerOnly
106781             };
106782         }
106783         // Collect the expected outputs of this project
106784         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106785         // Now see if all outputs are newer than the newest input
106786         var oldestOutputFileName = "(none)";
106787         var oldestOutputFileTime = maximumDate;
106788         var newestOutputFileName = "(none)";
106789         var newestOutputFileTime = minimumDate;
106790         var missingOutputFileName;
106791         var newestDeclarationFileContentChangedTime = minimumDate;
106792         var isOutOfDateWithInputs = false;
106793         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106794             var output = outputs_1[_b];
106795             // Output is missing; can stop checking
106796             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106797             if (!host.fileExists(output)) {
106798                 missingOutputFileName = output;
106799                 break;
106800             }
106801             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106802             if (outputTime < oldestOutputFileTime) {
106803                 oldestOutputFileTime = outputTime;
106804                 oldestOutputFileName = output;
106805             }
106806             // If an output is older than the newest input, we can stop checking
106807             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106808             if (outputTime < newestInputFileTime) {
106809                 isOutOfDateWithInputs = true;
106810                 break;
106811             }
106812             if (outputTime > newestOutputFileTime) {
106813                 newestOutputFileTime = outputTime;
106814                 newestOutputFileName = output;
106815             }
106816             // Keep track of when the most recent time a .d.ts file was changed.
106817             // In addition to file timestamps, we also keep track of when a .d.ts file
106818             // had its file touched but not had its contents changed - this allows us
106819             // to skip a downstream typecheck
106820             if (isDeclarationFile(output)) {
106821                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106822                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
106823             }
106824         }
106825         var pseudoUpToDate = false;
106826         var usesPrepend = false;
106827         var upstreamChangedProject;
106828         if (project.projectReferences) {
106829             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
106830             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
106831                 var ref = _d[_c];
106832                 usesPrepend = usesPrepend || !!(ref.prepend);
106833                 var resolvedRef = ts.resolveProjectReferencePath(ref);
106834                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
106835                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
106836                 // Its a circular reference ignore the status of this project
106837                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
106838                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
106839                     continue;
106840                 }
106841                 // An upstream project is blocked
106842                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
106843                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
106844                     return {
106845                         type: ts.UpToDateStatusType.UpstreamBlocked,
106846                         upstreamProjectName: ref.path,
106847                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
106848                     };
106849                 }
106850                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
106851                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
106852                     return {
106853                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
106854                         upstreamProjectName: ref.path
106855                     };
106856                 }
106857                 // Check oldest output file name only if there is no missing output file name
106858                 if (!missingOutputFileName) {
106859                     // If the upstream project's newest file is older than our oldest output, we
106860                     // can't be out of date because of it
106861                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
106862                         continue;
106863                     }
106864                     // If the upstream project has only change .d.ts files, and we've built
106865                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
106866                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
106867                         pseudoUpToDate = true;
106868                         upstreamChangedProject = ref.path;
106869                         continue;
106870                     }
106871                     // We have an output older than an upstream output - we are out of date
106872                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
106873                     return {
106874                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
106875                         outOfDateOutputFileName: oldestOutputFileName,
106876                         newerProjectName: ref.path
106877                     };
106878                 }
106879             }
106880         }
106881         if (missingOutputFileName !== undefined) {
106882             return {
106883                 type: ts.UpToDateStatusType.OutputMissing,
106884                 missingOutputFileName: missingOutputFileName
106885             };
106886         }
106887         if (isOutOfDateWithInputs) {
106888             return {
106889                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106890                 outOfDateOutputFileName: oldestOutputFileName,
106891                 newerInputFileName: newestInputFileName
106892             };
106893         }
106894         else {
106895             // Check tsconfig time
106896             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
106897             if (configStatus)
106898                 return configStatus;
106899             // Check extended config time
106900             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
106901             if (extendedConfigStatus)
106902                 return extendedConfigStatus;
106903         }
106904         if (!state.buildInfoChecked.has(resolvedPath)) {
106905             state.buildInfoChecked.set(resolvedPath, true);
106906             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
106907             if (buildInfoPath) {
106908                 var value = state.readFileWithCache(buildInfoPath);
106909                 var buildInfo = value && ts.getBuildInfo(value);
106910                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
106911                     return {
106912                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
106913                         version: buildInfo.version
106914                     };
106915                 }
106916             }
106917         }
106918         if (usesPrepend && pseudoUpToDate) {
106919             return {
106920                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
106921                 outOfDateOutputFileName: oldestOutputFileName,
106922                 newerProjectName: upstreamChangedProject
106923             };
106924         }
106925         // Up to date
106926         return {
106927             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
106928             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
106929             newestInputFileTime: newestInputFileTime,
106930             newestOutputFileTime: newestOutputFileTime,
106931             newestInputFileName: newestInputFileName,
106932             newestOutputFileName: newestOutputFileName,
106933             oldestOutputFileName: oldestOutputFileName
106934         };
106935     }
106936     function getUpToDateStatus(state, project, resolvedPath) {
106937         if (project === undefined) {
106938             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
106939         }
106940         var prior = state.projectStatus.get(resolvedPath);
106941         if (prior !== undefined) {
106942             return prior;
106943         }
106944         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
106945         state.projectStatus.set(resolvedPath, actual);
106946         return actual;
106947     }
106948     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
106949         var host = state.host;
106950         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
106951         if (!skipOutputs || outputs.length !== skipOutputs.size) {
106952             var reportVerbose = !!state.options.verbose;
106953             var now = host.now ? host.now() : new Date();
106954             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
106955                 var file = outputs_2[_i];
106956                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
106957                     continue;
106958                 }
106959                 if (reportVerbose) {
106960                     reportVerbose = false;
106961                     reportStatus(state, verboseMessage, proj.options.configFilePath);
106962                 }
106963                 if (isDeclarationFile(file)) {
106964                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
106965                 }
106966                 host.setModifiedTime(file, now);
106967             }
106968         }
106969         return priorNewestUpdateTime;
106970     }
106971     function updateOutputTimestamps(state, proj, resolvedPath) {
106972         if (state.options.dry) {
106973             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
106974         }
106975         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
106976         state.projectStatus.set(resolvedPath, {
106977             type: ts.UpToDateStatusType.UpToDate,
106978             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
106979             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
106980         });
106981     }
106982     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
106983         // Queue only if there are no errors
106984         if (buildResult & BuildResultFlags.AnyErrors)
106985             return;
106986         // Only composite projects can be referenced by other projects
106987         if (!config.options.composite)
106988             return;
106989         // Always use build order to queue projects
106990         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
106991             var nextProject = buildOrder[index];
106992             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
106993             if (state.projectPendingBuild.has(nextProjectPath))
106994                 continue;
106995             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
106996             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
106997                 continue;
106998             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
106999                 var ref = _a[_i];
107000                 var resolvedRefPath = resolveProjectName(state, ref.path);
107001                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107002                     continue;
107003                 // If the project is referenced with prepend, always build downstream projects,
107004                 // If declaration output is changed, build the project
107005                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107006                 var status = state.projectStatus.get(nextProjectPath);
107007                 if (status) {
107008                     switch (status.type) {
107009                         case ts.UpToDateStatusType.UpToDate:
107010                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107011                                 if (ref.prepend) {
107012                                     state.projectStatus.set(nextProjectPath, {
107013                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107014                                         outOfDateOutputFileName: status.oldestOutputFileName,
107015                                         newerProjectName: project
107016                                     });
107017                                 }
107018                                 else {
107019                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107020                                 }
107021                                 break;
107022                             }
107023                         // falls through
107024                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107025                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107026                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107027                                 state.projectStatus.set(nextProjectPath, {
107028                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107029                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107030                                     newerProjectName: project
107031                                 });
107032                             }
107033                             break;
107034                         case ts.UpToDateStatusType.UpstreamBlocked:
107035                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107036                                 clearProjectStatus(state, nextProjectPath);
107037                             }
107038                             break;
107039                     }
107040                 }
107041                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107042                 break;
107043             }
107044         }
107045     }
107046     function build(state, project, cancellationToken, onlyReferences) {
107047         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107048         if (!buildOrder)
107049             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107050         setupInitialBuild(state, cancellationToken);
107051         var reportQueue = true;
107052         var successfulProjects = 0;
107053         while (true) {
107054             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107055             if (!invalidatedProject)
107056                 break;
107057             reportQueue = false;
107058             invalidatedProject.done(cancellationToken);
107059             if (!state.diagnostics.has(invalidatedProject.projectPath))
107060                 successfulProjects++;
107061         }
107062         disableCache(state);
107063         reportErrorSummary(state, buildOrder);
107064         startWatching(state, buildOrder);
107065         return isCircularBuildOrder(buildOrder)
107066             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107067             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107068                 ? ts.ExitStatus.Success
107069                 : successfulProjects
107070                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107071                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107072     }
107073     function clean(state, project, onlyReferences) {
107074         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107075         if (!buildOrder)
107076             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107077         if (isCircularBuildOrder(buildOrder)) {
107078             reportErrors(state, buildOrder.circularDiagnostics);
107079             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107080         }
107081         var options = state.options, host = state.host;
107082         var filesToDelete = options.dry ? [] : undefined;
107083         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107084             var proj = buildOrder_1[_i];
107085             var resolvedPath = toResolvedConfigFilePath(state, proj);
107086             var parsed = parseConfigFile(state, proj, resolvedPath);
107087             if (parsed === undefined) {
107088                 // File has gone missing; fine to ignore here
107089                 reportParseConfigFileDiagnostic(state, resolvedPath);
107090                 continue;
107091             }
107092             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107093             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107094                 var output = outputs_3[_a];
107095                 if (host.fileExists(output)) {
107096                     if (filesToDelete) {
107097                         filesToDelete.push(output);
107098                     }
107099                     else {
107100                         host.deleteFile(output);
107101                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107102                     }
107103                 }
107104             }
107105         }
107106         if (filesToDelete) {
107107             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107108         }
107109         return ts.ExitStatus.Success;
107110     }
107111     function invalidateProject(state, resolved, reloadLevel) {
107112         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107113         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107114             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107115         }
107116         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107117             state.configFileCache.delete(resolved);
107118             state.buildOrder = undefined;
107119         }
107120         state.needsSummary = true;
107121         clearProjectStatus(state, resolved);
107122         addProjToQueue(state, resolved, reloadLevel);
107123         enableCache(state);
107124     }
107125     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107126         state.reportFileChangeDetected = true;
107127         invalidateProject(state, resolvedPath, reloadLevel);
107128         scheduleBuildInvalidatedProject(state);
107129     }
107130     function scheduleBuildInvalidatedProject(state) {
107131         var hostWithWatch = state.hostWithWatch;
107132         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107133             return;
107134         }
107135         if (state.timerToBuildInvalidatedProject) {
107136             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107137         }
107138         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107139     }
107140     function buildNextInvalidatedProject(state) {
107141         state.timerToBuildInvalidatedProject = undefined;
107142         if (state.reportFileChangeDetected) {
107143             state.reportFileChangeDetected = false;
107144             state.projectErrorsReported.clear();
107145             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107146         }
107147         var buildOrder = getBuildOrder(state);
107148         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107149         if (invalidatedProject) {
107150             invalidatedProject.done();
107151             if (state.projectPendingBuild.size) {
107152                 // Schedule next project for build
107153                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107154                     scheduleBuildInvalidatedProject(state);
107155                 }
107156                 return;
107157             }
107158         }
107159         disableCache(state);
107160         reportErrorSummary(state, buildOrder);
107161     }
107162     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107163         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107164             return;
107165         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107166             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107167         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107168     }
107169     function isSameFile(state, file1, file2) {
107170         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107171     }
107172     function isOutputFile(state, fileName, configFile) {
107173         if (configFile.options.noEmit)
107174             return false;
107175         // ts or tsx files are not output
107176         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107177             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107178             return false;
107179         }
107180         // If options have --outFile or --out, check if its that
107181         var out = configFile.options.outFile || configFile.options.out;
107182         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107183             return true;
107184         }
107185         // If declarationDir is specified, return if its a file in that directory
107186         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107187             return true;
107188         }
107189         // If --outDir, check if file is in that directory
107190         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107191             return true;
107192         }
107193         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107194     }
107195     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107196         if (!state.watch)
107197             return;
107198         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107199             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107200             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107201                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107202                 return;
107203             }
107204             if (isOutputFile(state, fileOrDirectory, parsed)) {
107205                 state.writeLog(fileOrDirectory + " is output file");
107206                 return;
107207             }
107208             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107209         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107210     }
107211     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107212         if (!state.watch)
107213             return;
107214         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107215             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); },
107216             onDeleteValue: ts.closeFileWatcher,
107217         });
107218     }
107219     function startWatching(state, buildOrder) {
107220         if (!state.watchAllProjectsPending)
107221             return;
107222         state.watchAllProjectsPending = false;
107223         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107224             var resolved = _a[_i];
107225             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107226             var cfg = parseConfigFile(state, resolved, resolvedPath);
107227             // Watch this file
107228             watchConfigFile(state, resolved, resolvedPath, cfg);
107229             if (cfg) {
107230                 // Update watchers for wildcard directories
107231                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107232                 // Watch input files
107233                 watchInputFiles(state, resolved, resolvedPath, cfg);
107234             }
107235         }
107236     }
107237     function stopWatching(state) {
107238         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107239         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107240         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107241     }
107242     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107243         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107244         return {
107245             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107246             clean: function (project) { return clean(state, project); },
107247             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107248             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107249             getNextInvalidatedProject: function (cancellationToken) {
107250                 setupInitialBuild(state, cancellationToken);
107251                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107252             },
107253             getBuildOrder: function () { return getBuildOrder(state); },
107254             getUpToDateStatusOfProject: function (project) {
107255                 var configFileName = resolveProjectName(state, project);
107256                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107257                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107258             },
107259             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107260             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107261             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107262             close: function () { return stopWatching(state); },
107263         };
107264     }
107265     function relName(state, path) {
107266         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107267     }
107268     function reportStatus(state, message) {
107269         var args = [];
107270         for (var _i = 2; _i < arguments.length; _i++) {
107271             args[_i - 2] = arguments[_i];
107272         }
107273         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107274     }
107275     function reportWatchStatus(state, message) {
107276         var args = [];
107277         for (var _i = 2; _i < arguments.length; _i++) {
107278             args[_i - 2] = arguments[_i];
107279         }
107280         if (state.hostWithWatch.onWatchStatusChange) {
107281             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107282         }
107283     }
107284     function reportErrors(_a, errors) {
107285         var host = _a.host;
107286         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107287     }
107288     function reportAndStoreErrors(state, proj, errors) {
107289         reportErrors(state, errors);
107290         state.projectErrorsReported.set(proj, true);
107291         if (errors.length) {
107292             state.diagnostics.set(proj, errors);
107293         }
107294     }
107295     function reportParseConfigFileDiagnostic(state, proj) {
107296         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107297     }
107298     function reportErrorSummary(state, buildOrder) {
107299         if (!state.needsSummary)
107300             return;
107301         state.needsSummary = false;
107302         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107303         var diagnostics = state.diagnostics;
107304         var totalErrors = 0;
107305         if (isCircularBuildOrder(buildOrder)) {
107306             reportBuildQueue(state, buildOrder.buildOrder);
107307             reportErrors(state, buildOrder.circularDiagnostics);
107308             if (canReportSummary)
107309                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107310         }
107311         else {
107312             // Report errors from the other projects
107313             buildOrder.forEach(function (project) {
107314                 var projectPath = toResolvedConfigFilePath(state, project);
107315                 if (!state.projectErrorsReported.has(projectPath)) {
107316                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107317                 }
107318             });
107319             if (canReportSummary)
107320                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107321         }
107322         if (state.watch) {
107323             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107324         }
107325         else if (state.host.reportErrorSummary) {
107326             state.host.reportErrorSummary(totalErrors);
107327         }
107328     }
107329     /**
107330      * Report the build ordering inferred from the current project graph if we're in verbose mode
107331      */
107332     function reportBuildQueue(state, buildQueue) {
107333         if (state.options.verbose) {
107334             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107335         }
107336     }
107337     function reportUpToDateStatus(state, configFileName, status) {
107338         switch (status.type) {
107339             case ts.UpToDateStatusType.OutOfDateWithSelf:
107340                 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));
107341             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107342                 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));
107343             case ts.UpToDateStatusType.OutputMissing:
107344                 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));
107345             case ts.UpToDateStatusType.UpToDate:
107346                 if (status.newestInputFileTime !== undefined) {
107347                     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 || ""));
107348                 }
107349                 // Don't report anything for "up to date because it was already built" -- too verbose
107350                 break;
107351             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107352                 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));
107353             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107354                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107355             case ts.UpToDateStatusType.UpstreamOutOfDate:
107356                 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));
107357             case ts.UpToDateStatusType.UpstreamBlocked:
107358                 return reportStatus(state, status.upstreamProjectBlocked ?
107359                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107360                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107361             case ts.UpToDateStatusType.Unbuildable:
107362                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107363             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107364                 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);
107365             case ts.UpToDateStatusType.ContainerOnly:
107366             // Don't report status on "solution" projects
107367             // falls through
107368             case ts.UpToDateStatusType.ComputingUpstream:
107369                 // Should never leak from getUptoDateStatusWorker
107370                 break;
107371             default:
107372                 ts.assertType(status);
107373         }
107374     }
107375     /**
107376      * Report the up-to-date status of a project if we're in verbose mode
107377      */
107378     function verboseReportProjectStatus(state, configFileName, status) {
107379         if (state.options.verbose) {
107380             reportUpToDateStatus(state, configFileName, status);
107381         }
107382     }
107383 })(ts || (ts = {}));
107384 var ts;
107385 (function (ts) {
107386     var server;
107387     (function (server) {
107388         /* @internal */
107389         server.ActionSet = "action::set";
107390         /* @internal */
107391         server.ActionInvalidate = "action::invalidate";
107392         /* @internal */
107393         server.ActionPackageInstalled = "action::packageInstalled";
107394         /* @internal */
107395         server.EventTypesRegistry = "event::typesRegistry";
107396         /* @internal */
107397         server.EventBeginInstallTypes = "event::beginInstallTypes";
107398         /* @internal */
107399         server.EventEndInstallTypes = "event::endInstallTypes";
107400         /* @internal */
107401         server.EventInitializationFailed = "event::initializationFailed";
107402         /* @internal */
107403         var Arguments;
107404         (function (Arguments) {
107405             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
107406             Arguments.LogFile = "--logFile";
107407             Arguments.EnableTelemetry = "--enableTelemetry";
107408             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
107409             Arguments.TypesMapLocation = "--typesMapLocation";
107410             /**
107411              * This argument specifies the location of the NPM executable.
107412              * typingsInstaller will run the command with `${npmLocation} install ...`.
107413              */
107414             Arguments.NpmLocation = "--npmLocation";
107415             /**
107416              * Flag indicating that the typings installer should try to validate the default npm location.
107417              * If the default npm is not found when this flag is enabled, fallback to `npm install`
107418              */
107419             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
107420         })(Arguments = server.Arguments || (server.Arguments = {}));
107421         /* @internal */
107422         function hasArgument(argumentName) {
107423             return ts.sys.args.indexOf(argumentName) >= 0;
107424         }
107425         server.hasArgument = hasArgument;
107426         /* @internal */
107427         function findArgument(argumentName) {
107428             var index = ts.sys.args.indexOf(argumentName);
107429             return index >= 0 && index < ts.sys.args.length - 1
107430                 ? ts.sys.args[index + 1]
107431                 : undefined;
107432         }
107433         server.findArgument = findArgument;
107434         /* @internal */
107435         function nowString() {
107436             // E.g. "12:34:56.789"
107437             var d = new Date();
107438             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
107439         }
107440         server.nowString = nowString;
107441     })(server = ts.server || (ts.server = {}));
107442 })(ts || (ts = {}));
107443 /* @internal */
107444 var ts;
107445 (function (ts) {
107446     var JsTyping;
107447     (function (JsTyping) {
107448         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
107449             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
107450             return availableVersion.compareTo(cachedTyping.version) <= 0;
107451         }
107452         JsTyping.isTypingUpToDate = isTypingUpToDate;
107453         JsTyping.nodeCoreModuleList = [
107454             "assert",
107455             "async_hooks",
107456             "buffer",
107457             "child_process",
107458             "cluster",
107459             "console",
107460             "constants",
107461             "crypto",
107462             "dgram",
107463             "dns",
107464             "domain",
107465             "events",
107466             "fs",
107467             "http",
107468             "https",
107469             "http2",
107470             "inspector",
107471             "net",
107472             "os",
107473             "path",
107474             "perf_hooks",
107475             "process",
107476             "punycode",
107477             "querystring",
107478             "readline",
107479             "repl",
107480             "stream",
107481             "string_decoder",
107482             "timers",
107483             "tls",
107484             "tty",
107485             "url",
107486             "util",
107487             "v8",
107488             "vm",
107489             "zlib"
107490         ];
107491         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
107492         function nonRelativeModuleNameForTypingCache(moduleName) {
107493             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
107494         }
107495         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
107496         function loadSafeList(host, safeListPath) {
107497             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
107498             return ts.createMapFromTemplate(result.config);
107499         }
107500         JsTyping.loadSafeList = loadSafeList;
107501         function loadTypesMap(host, typesMapPath) {
107502             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
107503             if (result.config) {
107504                 return ts.createMapFromTemplate(result.config.simpleMap);
107505             }
107506             return undefined;
107507         }
107508         JsTyping.loadTypesMap = loadTypesMap;
107509         /**
107510          * @param host is the object providing I/O related operations.
107511          * @param fileNames are the file names that belong to the same project
107512          * @param projectRootPath is the path to the project root directory
107513          * @param safeListPath is the path used to retrieve the safe list
107514          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
107515          * @param typeAcquisition is used to customize the typing acquisition process
107516          * @param compilerOptions are used as a source for typing inference
107517          */
107518         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
107519             if (!typeAcquisition || !typeAcquisition.enable) {
107520                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
107521             }
107522             // A typing name to typing file path mapping
107523             var inferredTypings = ts.createMap();
107524             // Only infer typings for .js and .jsx files
107525             fileNames = ts.mapDefined(fileNames, function (fileName) {
107526                 var path = ts.normalizePath(fileName);
107527                 if (ts.hasJSFileExtension(path)) {
107528                     return path;
107529                 }
107530             });
107531             var filesToWatch = [];
107532             if (typeAcquisition.include)
107533                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
107534             var exclude = typeAcquisition.exclude || [];
107535             // Directories to search for package.json, bower.json and other typing information
107536             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
107537             possibleSearchDirs.set(projectRootPath, true);
107538             possibleSearchDirs.forEach(function (_true, searchDir) {
107539                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
107540                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
107541                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
107542                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
107543                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
107544                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
107545                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
107546                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
107547             });
107548             getTypingNamesFromSourceFileNames(fileNames);
107549             // add typings for unresolved imports
107550             if (unresolvedImports) {
107551                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
107552                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
107553             }
107554             // Add the cached typing locations for inferred typings that are already installed
107555             packageNameToTypingLocation.forEach(function (typing, name) {
107556                 var registryEntry = typesRegistry.get(name);
107557                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
107558                     inferredTypings.set(name, typing.typingLocation);
107559                 }
107560             });
107561             // Remove typings that the user has added to the exclude list
107562             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
107563                 var excludeTypingName = exclude_1[_i];
107564                 var didDelete = inferredTypings.delete(excludeTypingName);
107565                 if (didDelete && log)
107566                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
107567             }
107568             var newTypingNames = [];
107569             var cachedTypingPaths = [];
107570             inferredTypings.forEach(function (inferred, typing) {
107571                 if (inferred !== undefined) {
107572                     cachedTypingPaths.push(inferred);
107573                 }
107574                 else {
107575                     newTypingNames.push(typing);
107576                 }
107577             });
107578             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
107579             if (log)
107580                 log("Result: " + JSON.stringify(result));
107581             return result;
107582             function addInferredTyping(typingName) {
107583                 if (!inferredTypings.has(typingName)) {
107584                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
107585                 }
107586             }
107587             function addInferredTypings(typingNames, message) {
107588                 if (log)
107589                     log(message + ": " + JSON.stringify(typingNames));
107590                 ts.forEach(typingNames, addInferredTyping);
107591             }
107592             /**
107593              * Get the typing info from common package manager json files like package.json or bower.json
107594              */
107595             function getTypingNamesFromJson(jsonPath, filesToWatch) {
107596                 if (!host.fileExists(jsonPath)) {
107597                     return;
107598                 }
107599                 filesToWatch.push(jsonPath);
107600                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
107601                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
107602                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
107603             }
107604             /**
107605              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
107606              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
107607              * to the 'angular-route' typing name.
107608              * @param fileNames are the names for source files in the project
107609              */
107610             function getTypingNamesFromSourceFileNames(fileNames) {
107611                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
107612                     if (!ts.hasJSFileExtension(j))
107613                         return undefined;
107614                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
107615                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
107616                     return safeList.get(cleanedTypingName);
107617                 });
107618                 if (fromFileNames.length) {
107619                     addInferredTypings(fromFileNames, "Inferred typings from file names");
107620                 }
107621                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
107622                 if (hasJsxFile) {
107623                     if (log)
107624                         log("Inferred 'react' typings due to presence of '.jsx' extension");
107625                     addInferredTyping("react");
107626                 }
107627             }
107628             /**
107629              * Infer typing names from packages folder (ex: node_module, bower_components)
107630              * @param packagesFolderPath is the path to the packages folder
107631              */
107632             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
107633                 filesToWatch.push(packagesFolderPath);
107634                 // Todo: add support for ModuleResolutionHost too
107635                 if (!host.directoryExists(packagesFolderPath)) {
107636                     return;
107637                 }
107638                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
107639                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
107640                 if (log)
107641                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
107642                 var packageNames = [];
107643                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
107644                     var fileName = fileNames_1[_i];
107645                     var normalizedFileName = ts.normalizePath(fileName);
107646                     var baseFileName = ts.getBaseFileName(normalizedFileName);
107647                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
107648                         continue;
107649                     }
107650                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
107651                     var packageJson = result_1.config;
107652                     // npm 3's package.json contains a "_requiredBy" field
107653                     // we should include all the top level module names for npm 2, and only module names whose
107654                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
107655                     if (baseFileName === "package.json" && packageJson._requiredBy &&
107656                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
107657                         continue;
107658                     }
107659                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
107660                     // to download d.ts files from DefinitelyTyped
107661                     if (!packageJson.name) {
107662                         continue;
107663                     }
107664                     var ownTypes = packageJson.types || packageJson.typings;
107665                     if (ownTypes) {
107666                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
107667                         if (log)
107668                             log("    Package '" + packageJson.name + "' provides its own types.");
107669                         inferredTypings.set(packageJson.name, absolutePath);
107670                     }
107671                     else {
107672                         packageNames.push(packageJson.name);
107673                     }
107674                 }
107675                 addInferredTypings(packageNames, "    Found package names");
107676             }
107677         }
107678         JsTyping.discoverTypings = discoverTypings;
107679         var NameValidationResult;
107680         (function (NameValidationResult) {
107681             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
107682             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
107683             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
107684             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
107685             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
107686             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
107687         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
107688         var maxPackageNameLength = 214;
107689         /**
107690          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
107691          */
107692         function validatePackageName(packageName) {
107693             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
107694         }
107695         JsTyping.validatePackageName = validatePackageName;
107696         function validatePackageNameWorker(packageName, supportScopedPackage) {
107697             if (!packageName) {
107698                 return 1 /* EmptyName */;
107699             }
107700             if (packageName.length > maxPackageNameLength) {
107701                 return 2 /* NameTooLong */;
107702             }
107703             if (packageName.charCodeAt(0) === 46 /* dot */) {
107704                 return 3 /* NameStartsWithDot */;
107705             }
107706             if (packageName.charCodeAt(0) === 95 /* _ */) {
107707                 return 4 /* NameStartsWithUnderscore */;
107708             }
107709             // check if name is scope package like: starts with @ and has one '/' in the middle
107710             // scoped packages are not currently supported
107711             if (supportScopedPackage) {
107712                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
107713                 if (matches) {
107714                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
107715                     if (scopeResult !== 0 /* Ok */) {
107716                         return { name: matches[1], isScopeName: true, result: scopeResult };
107717                     }
107718                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
107719                     if (packageResult !== 0 /* Ok */) {
107720                         return { name: matches[2], isScopeName: false, result: packageResult };
107721                     }
107722                     return 0 /* Ok */;
107723                 }
107724             }
107725             if (encodeURIComponent(packageName) !== packageName) {
107726                 return 5 /* NameContainsNonURISafeCharacters */;
107727             }
107728             return 0 /* Ok */;
107729         }
107730         function renderPackageNameValidationFailure(result, typing) {
107731             return typeof result === "object" ?
107732                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
107733                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
107734         }
107735         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
107736         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
107737             var kind = isScopeName ? "Scope" : "Package";
107738             switch (result) {
107739                 case 1 /* EmptyName */:
107740                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
107741                 case 2 /* NameTooLong */:
107742                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
107743                 case 3 /* NameStartsWithDot */:
107744                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
107745                 case 4 /* NameStartsWithUnderscore */:
107746                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
107747                 case 5 /* NameContainsNonURISafeCharacters */:
107748                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
107749                 case 0 /* Ok */:
107750                     return ts.Debug.fail(); // Shouldn't have called this.
107751                 default:
107752                     throw ts.Debug.assertNever(result);
107753             }
107754         }
107755     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
107756 })(ts || (ts = {}));
107757 var ts;
107758 (function (ts) {
107759     var server;
107760     (function (server) {
107761         var typingsInstaller;
107762         (function (typingsInstaller) {
107763             var nullLog = {
107764                 isEnabled: function () { return false; },
107765                 writeLine: ts.noop
107766             };
107767             function typingToFileName(cachePath, packageName, installTypingHost, log) {
107768                 try {
107769                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
107770                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
107771                 }
107772                 catch (e) {
107773                     if (log.isEnabled()) {
107774                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
107775                     }
107776                     return undefined;
107777                 }
107778             }
107779             /*@internal*/
107780             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
107781                 var hasError = false;
107782                 for (var remaining = packageNames.length; remaining > 0;) {
107783                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
107784                     remaining = result.remaining;
107785                     hasError = install(result.command) || hasError;
107786                 }
107787                 return hasError;
107788             }
107789             typingsInstaller.installNpmPackages = installNpmPackages;
107790             /*@internal*/
107791             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
107792                 var sliceStart = packageNames.length - remaining;
107793                 var command, toSlice = remaining;
107794                 while (true) {
107795                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
107796                     if (command.length < 8000) {
107797                         break;
107798                     }
107799                     toSlice = toSlice - Math.floor(toSlice / 2);
107800                 }
107801                 return { command: command, remaining: remaining - toSlice };
107802             }
107803             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
107804             function endsWith(str, suffix, caseSensitive) {
107805                 var expectedPos = str.length - suffix.length;
107806                 return expectedPos >= 0 &&
107807                     (str.indexOf(suffix, expectedPos) === expectedPos ||
107808                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
107809             }
107810             function isPackageOrBowerJson(fileName, caseSensitive) {
107811                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
107812             }
107813             function sameFiles(a, b, caseSensitive) {
107814                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
107815             }
107816             var ProjectWatcherType;
107817             (function (ProjectWatcherType) {
107818                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
107819                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
107820             })(ProjectWatcherType || (ProjectWatcherType = {}));
107821             var TypingsInstaller = /** @class */ (function () {
107822                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
107823                     if (log === void 0) { log = nullLog; }
107824                     this.installTypingHost = installTypingHost;
107825                     this.globalCachePath = globalCachePath;
107826                     this.safeListPath = safeListPath;
107827                     this.typesMapLocation = typesMapLocation;
107828                     this.throttleLimit = throttleLimit;
107829                     this.log = log;
107830                     this.packageNameToTypingLocation = ts.createMap();
107831                     this.missingTypingsSet = ts.createMap();
107832                     this.knownCachesSet = ts.createMap();
107833                     this.projectWatchers = ts.createMap();
107834                     this.pendingRunRequests = [];
107835                     this.installRunCount = 1;
107836                     this.inFlightRequestCount = 0;
107837                     this.latestDistTag = "latest";
107838                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
107839                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
107840                     if (this.log.isEnabled()) {
107841                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
107842                     }
107843                     this.processCacheLocation(this.globalCachePath);
107844                 }
107845                 TypingsInstaller.prototype.closeProject = function (req) {
107846                     this.closeWatchers(req.projectName);
107847                 };
107848                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
107849                     if (this.log.isEnabled()) {
107850                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
107851                     }
107852                     var watchers = this.projectWatchers.get(projectName);
107853                     if (!watchers) {
107854                         if (this.log.isEnabled()) {
107855                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
107856                         }
107857                         return;
107858                     }
107859                     ts.clearMap(watchers, ts.closeFileWatcher);
107860                     this.projectWatchers.delete(projectName);
107861                     if (this.log.isEnabled()) {
107862                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
107863                     }
107864                 };
107865                 TypingsInstaller.prototype.install = function (req) {
107866                     var _this = this;
107867                     if (this.log.isEnabled()) {
107868                         this.log.writeLine("Got install request " + JSON.stringify(req));
107869                     }
107870                     // load existing typing information from the cache
107871                     if (req.cachePath) {
107872                         if (this.log.isEnabled()) {
107873                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
107874                         }
107875                         this.processCacheLocation(req.cachePath);
107876                     }
107877                     if (this.safeList === undefined) {
107878                         this.initializeSafeList();
107879                     }
107880                     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);
107881                     if (this.log.isEnabled()) {
107882                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
107883                     }
107884                     // start watching files
107885                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
107886                     // install typings
107887                     if (discoverTypingsResult.newTypingNames.length) {
107888                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
107889                     }
107890                     else {
107891                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
107892                         if (this.log.isEnabled()) {
107893                             this.log.writeLine("No new typings were requested as a result of typings discovery");
107894                         }
107895                     }
107896                 };
107897                 TypingsInstaller.prototype.initializeSafeList = function () {
107898                     // Prefer the safe list from the types map if it exists
107899                     if (this.typesMapLocation) {
107900                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
107901                         if (safeListFromMap) {
107902                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
107903                             this.safeList = safeListFromMap;
107904                             return;
107905                         }
107906                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
107907                     }
107908                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
107909                 };
107910                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
107911                     if (this.log.isEnabled()) {
107912                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
107913                     }
107914                     if (this.knownCachesSet.has(cacheLocation)) {
107915                         if (this.log.isEnabled()) {
107916                             this.log.writeLine("Cache location was already processed...");
107917                         }
107918                         return;
107919                     }
107920                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
107921                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
107922                     if (this.log.isEnabled()) {
107923                         this.log.writeLine("Trying to find '" + packageJson + "'...");
107924                     }
107925                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
107926                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
107927                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
107928                         if (this.log.isEnabled()) {
107929                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
107930                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
107931                         }
107932                         if (npmConfig.devDependencies && npmLock.dependencies) {
107933                             for (var key in npmConfig.devDependencies) {
107934                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
107935                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
107936                                     continue;
107937                                 }
107938                                 // key is @types/<package name>
107939                                 var packageName = ts.getBaseFileName(key);
107940                                 if (!packageName) {
107941                                     continue;
107942                                 }
107943                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
107944                                 if (!typingFile) {
107945                                     this.missingTypingsSet.set(packageName, true);
107946                                     continue;
107947                                 }
107948                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
107949                                 if (existingTypingFile) {
107950                                     if (existingTypingFile.typingLocation === typingFile) {
107951                                         continue;
107952                                     }
107953                                     if (this.log.isEnabled()) {
107954                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
107955                                     }
107956                                 }
107957                                 if (this.log.isEnabled()) {
107958                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
107959                                 }
107960                                 var info = ts.getProperty(npmLock.dependencies, key);
107961                                 var version_1 = info && info.version;
107962                                 if (!version_1) {
107963                                     continue;
107964                                 }
107965                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
107966                                 this.packageNameToTypingLocation.set(packageName, newTyping);
107967                             }
107968                         }
107969                     }
107970                     if (this.log.isEnabled()) {
107971                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
107972                     }
107973                     this.knownCachesSet.set(cacheLocation, true);
107974                 };
107975                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
107976                     var _this = this;
107977                     return ts.mapDefined(typingsToInstall, function (typing) {
107978                         var typingKey = ts.mangleScopedPackageName(typing);
107979                         if (_this.missingTypingsSet.get(typingKey)) {
107980                             if (_this.log.isEnabled())
107981                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
107982                             return undefined;
107983                         }
107984                         var validationResult = ts.JsTyping.validatePackageName(typing);
107985                         if (validationResult !== 0 /* Ok */) {
107986                             // add typing name to missing set so we won't process it again
107987                             _this.missingTypingsSet.set(typingKey, true);
107988                             if (_this.log.isEnabled())
107989                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
107990                             return undefined;
107991                         }
107992                         if (!_this.typesRegistry.has(typingKey)) {
107993                             if (_this.log.isEnabled())
107994                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
107995                             return undefined;
107996                         }
107997                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
107998                             if (_this.log.isEnabled())
107999                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
108000                             return undefined;
108001                         }
108002                         return typingKey;
108003                     });
108004                 };
108005                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
108006                     var npmConfigPath = ts.combinePaths(directory, "package.json");
108007                     if (this.log.isEnabled()) {
108008                         this.log.writeLine("Npm config file: " + npmConfigPath);
108009                     }
108010                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
108011                         if (this.log.isEnabled()) {
108012                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
108013                         }
108014                         this.ensureDirectoryExists(directory, this.installTypingHost);
108015                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
108016                     }
108017                 };
108018                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
108019                     var _this = this;
108020                     if (this.log.isEnabled()) {
108021                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
108022                     }
108023                     var filteredTypings = this.filterTypings(typingsToInstall);
108024                     if (filteredTypings.length === 0) {
108025                         if (this.log.isEnabled()) {
108026                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
108027                         }
108028                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
108029                         return;
108030                     }
108031                     this.ensurePackageDirectoryExists(cachePath);
108032                     var requestId = this.installRunCount;
108033                     this.installRunCount++;
108034                     // send progress event
108035                     this.sendResponse({
108036                         kind: server.EventBeginInstallTypes,
108037                         eventId: requestId,
108038                         // qualified explicitly to prevent occasional shadowing
108039                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108040                         typingsInstallerVersion: ts.version,
108041                         projectName: req.projectName
108042                     });
108043                     var scopedTypings = filteredTypings.map(typingsName);
108044                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
108045                         try {
108046                             if (!ok) {
108047                                 if (_this.log.isEnabled()) {
108048                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
108049                                 }
108050                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
108051                                     var typing = filteredTypings_1[_i];
108052                                     _this.missingTypingsSet.set(typing, true);
108053                                 }
108054                                 return;
108055                             }
108056                             // TODO: watch project directory
108057                             if (_this.log.isEnabled()) {
108058                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
108059                             }
108060                             var installedTypingFiles = [];
108061                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
108062                                 var packageName = filteredTypings_2[_a];
108063                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
108064                                 if (!typingFile) {
108065                                     _this.missingTypingsSet.set(packageName, true);
108066                                     continue;
108067                                 }
108068                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
108069                                 var distTags = _this.typesRegistry.get(packageName);
108070                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
108071                                 var newTyping = { typingLocation: typingFile, version: newVersion };
108072                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
108073                                 installedTypingFiles.push(typingFile);
108074                             }
108075                             if (_this.log.isEnabled()) {
108076                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
108077                             }
108078                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
108079                         }
108080                         finally {
108081                             var response = {
108082                                 kind: server.EventEndInstallTypes,
108083                                 eventId: requestId,
108084                                 projectName: req.projectName,
108085                                 packagesToInstall: scopedTypings,
108086                                 installSuccess: ok,
108087                                 // qualified explicitly to prevent occasional shadowing
108088                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108089                                 typingsInstallerVersion: ts.version
108090                             };
108091                             _this.sendResponse(response);
108092                         }
108093                     });
108094                 };
108095                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
108096                     var directoryName = ts.getDirectoryPath(directory);
108097                     if (!host.directoryExists(directoryName)) {
108098                         this.ensureDirectoryExists(directoryName, host);
108099                     }
108100                     if (!host.directoryExists(directory)) {
108101                         host.createDirectory(directory);
108102                     }
108103                 };
108104                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
108105                     var _this = this;
108106                     if (!files.length) {
108107                         // shut down existing watchers
108108                         this.closeWatchers(projectName);
108109                         return;
108110                     }
108111                     var watchers = this.projectWatchers.get(projectName);
108112                     var toRemove = ts.createMap();
108113                     if (!watchers) {
108114                         watchers = ts.createMap();
108115                         this.projectWatchers.set(projectName, watchers);
108116                     }
108117                     else {
108118                         ts.copyEntries(watchers, toRemove);
108119                     }
108120                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
108121                     watchers.isInvoked = false;
108122                     var isLoggingEnabled = this.log.isEnabled();
108123                     var createProjectWatcher = function (path, projectWatcherType) {
108124                         var canonicalPath = _this.toCanonicalFileName(path);
108125                         toRemove.delete(canonicalPath);
108126                         if (watchers.has(canonicalPath)) {
108127                             return;
108128                         }
108129                         if (isLoggingEnabled) {
108130                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
108131                         }
108132                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
108133                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
108134                                 if (isLoggingEnabled) {
108135                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
108136                                 }
108137                                 if (!watchers.isInvoked) {
108138                                     watchers.isInvoked = true;
108139                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108140                                 }
108141                             }, /*pollingInterval*/ 2000, options) :
108142                             _this.installTypingHost.watchDirectory(path, function (f) {
108143                                 if (isLoggingEnabled) {
108144                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
108145                                 }
108146                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
108147                                     return;
108148                                 }
108149                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
108150                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
108151                                     watchers.isInvoked = true;
108152                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108153                                 }
108154                             }, /*recursive*/ true, options);
108155                         watchers.set(canonicalPath, isLoggingEnabled ? {
108156                             close: function () {
108157                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
108158                                 watcher.close();
108159                             }
108160                         } : watcher);
108161                     };
108162                     // Create watches from list of files
108163                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
108164                         var file = files_1[_i];
108165                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
108166                             // package.json or bower.json exists, watch the file to detect changes and update typings
108167                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
108168                             continue;
108169                         }
108170                         // path in projectRoot, watch project root
108171                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108172                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
108173                             if (subDirectory !== -1) {
108174                                 // Watch subDirectory
108175                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
108176                             }
108177                             else {
108178                                 // Watch the directory itself
108179                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108180                             }
108181                             continue;
108182                         }
108183                         // path in global cache, watch global cache
108184                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108185                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
108186                             continue;
108187                         }
108188                         // watch node_modules or bower_components
108189                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108190                     }
108191                     // Remove unused watches
108192                     toRemove.forEach(function (watch, path) {
108193                         watch.close();
108194                         watchers.delete(path);
108195                     });
108196                 };
108197                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
108198                     return {
108199                         projectName: request.projectName,
108200                         typeAcquisition: request.typeAcquisition,
108201                         compilerOptions: request.compilerOptions,
108202                         typings: typings,
108203                         unresolvedImports: request.unresolvedImports,
108204                         kind: server.ActionSet
108205                     };
108206                 };
108207                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
108208                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
108209                     this.executeWithThrottling();
108210                 };
108211                 TypingsInstaller.prototype.executeWithThrottling = function () {
108212                     var _this = this;
108213                     var _loop_1 = function () {
108214                         this_1.inFlightRequestCount++;
108215                         var request = this_1.pendingRunRequests.pop();
108216                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
108217                             _this.inFlightRequestCount--;
108218                             request.onRequestCompleted(ok);
108219                             _this.executeWithThrottling();
108220                         });
108221                     };
108222                     var this_1 = this;
108223                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
108224                         _loop_1();
108225                     }
108226                 };
108227                 return TypingsInstaller;
108228             }());
108229             typingsInstaller.TypingsInstaller = TypingsInstaller;
108230             /* @internal */
108231             function typingsName(packageName) {
108232                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
108233             }
108234             typingsInstaller.typingsName = typingsName;
108235         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108236     })(server = ts.server || (ts.server = {}));
108237 })(ts || (ts = {}));
108238 var ts;
108239 (function (ts) {
108240     var server;
108241     (function (server) {
108242         var typingsInstaller;
108243         (function (typingsInstaller) {
108244             var fs = require("fs");
108245             var path = require("path");
108246             var FileLog = (function () {
108247                 function FileLog(logFile) {
108248                     var _this = this;
108249                     this.logFile = logFile;
108250                     this.isEnabled = function () {
108251                         return typeof _this.logFile === "string";
108252                     };
108253                     this.writeLine = function (text) {
108254                         if (typeof _this.logFile !== "string")
108255                             return;
108256                         try {
108257                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
108258                         }
108259                         catch (e) {
108260                             _this.logFile = undefined;
108261                         }
108262                     };
108263                 }
108264                 return FileLog;
108265             }());
108266             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
108267                 if (path.basename(processName).indexOf("node") === 0) {
108268                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
108269                     if (!validateDefaultNpmLocation) {
108270                         return npmPath;
108271                     }
108272                     if (host.fileExists(npmPath)) {
108273                         return "\"" + npmPath + "\"";
108274                     }
108275                 }
108276                 return "npm";
108277             }
108278             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
108279                 if (!host.fileExists(typesRegistryFilePath)) {
108280                     if (log.isEnabled()) {
108281                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
108282                     }
108283                     return ts.createMap();
108284                 }
108285                 try {
108286                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
108287                     return ts.createMapFromTemplate(content.entries);
108288                 }
108289                 catch (e) {
108290                     if (log.isEnabled()) {
108291                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
108292                     }
108293                     return ts.createMap();
108294                 }
108295             }
108296             var typesRegistryPackageName = "types-registry";
108297             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
108298                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
108299             }
108300             var NodeTypingsInstaller = (function (_super) {
108301                 __extends(NodeTypingsInstaller, _super);
108302                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
108303                     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;
108304                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
108305                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
108306                         _this.npmPath = "\"" + _this.npmPath + "\"";
108307                     }
108308                     if (_this.log.isEnabled()) {
108309                         _this.log.writeLine("Process id: " + process.pid);
108310                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
108311                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
108312                     }
108313                     (_this.nodeExecSync = require("child_process").execSync);
108314                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
108315                     try {
108316                         if (_this.log.isEnabled()) {
108317                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
108318                         }
108319                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
108320                         if (_this.log.isEnabled()) {
108321                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
108322                         }
108323                     }
108324                     catch (e) {
108325                         if (_this.log.isEnabled()) {
108326                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
108327                         }
108328                         _this.delayedInitializationError = {
108329                             kind: "event::initializationFailed",
108330                             message: e.message
108331                         };
108332                     }
108333                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
108334                     return _this;
108335                 }
108336                 NodeTypingsInstaller.prototype.listen = function () {
108337                     var _this = this;
108338                     process.on("message", function (req) {
108339                         if (_this.delayedInitializationError) {
108340                             _this.sendResponse(_this.delayedInitializationError);
108341                             _this.delayedInitializationError = undefined;
108342                         }
108343                         switch (req.kind) {
108344                             case "discover":
108345                                 _this.install(req);
108346                                 break;
108347                             case "closeProject":
108348                                 _this.closeProject(req);
108349                                 break;
108350                             case "typesRegistry": {
108351                                 var typesRegistry_1 = {};
108352                                 _this.typesRegistry.forEach(function (value, key) {
108353                                     typesRegistry_1[key] = value;
108354                                 });
108355                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
108356                                 _this.sendResponse(response);
108357                                 break;
108358                             }
108359                             case "installPackage": {
108360                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
108361                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
108362                                 if (cwd) {
108363                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
108364                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
108365                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
108366                                         _this.sendResponse(response);
108367                                     });
108368                                 }
108369                                 else {
108370                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
108371                                     _this.sendResponse(response);
108372                                 }
108373                                 break;
108374                             }
108375                             default:
108376                                 ts.Debug.assertNever(req);
108377                         }
108378                     });
108379                 };
108380                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
108381                     if (this.log.isEnabled()) {
108382                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
108383                     }
108384                     process.send(response);
108385                     if (this.log.isEnabled()) {
108386                         this.log.writeLine("Response has been sent.");
108387                     }
108388                 };
108389                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
108390                     var _this = this;
108391                     if (this.log.isEnabled()) {
108392                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
108393                     }
108394                     var start = Date.now();
108395                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
108396                     if (this.log.isEnabled()) {
108397                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
108398                     }
108399                     onRequestCompleted(!hasError);
108400                 };
108401                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
108402                     if (this.log.isEnabled()) {
108403                         this.log.writeLine("Exec: " + command);
108404                     }
108405                     try {
108406                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
108407                         if (this.log.isEnabled()) {
108408                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
108409                         }
108410                         return false;
108411                     }
108412                     catch (error) {
108413                         var stdout = error.stdout, stderr = error.stderr;
108414                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
108415                         return true;
108416                     }
108417                 };
108418                 return NodeTypingsInstaller;
108419             }(typingsInstaller.TypingsInstaller));
108420             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
108421             function getDirectoryOfPackageJson(fileName, host) {
108422                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
108423                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
108424                         return directory;
108425                     }
108426                 });
108427             }
108428             var logFilePath = server.findArgument(server.Arguments.LogFile);
108429             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
108430             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
108431             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
108432             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
108433             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
108434             var log = new FileLog(logFilePath);
108435             if (log.isEnabled()) {
108436                 process.on("uncaughtException", function (e) {
108437                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
108438                 });
108439             }
108440             process.on("disconnect", function () {
108441                 if (log.isEnabled()) {
108442                     log.writeLine("Parent process has exited, shutting down...");
108443                 }
108444                 process.exit(0);
108445             });
108446             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
108447             installer.listen();
108448             function indent(newline, str) {
108449                 return newline + "    " + str.replace(/\r?\n/, newline + "    ");
108450             }
108451         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108452     })(server = ts.server || (ts.server = {}));
108453 })(ts || (ts = {}));
108454 //# sourceMappingURL=typingsInstaller.js.map